Community
Participate
Working Groups
A couple of times recently I have been bitten by a very hard-to-track bug to do with containers that contain autoboxed types, e.g. Integer. If there is a method .get(Object key) and a method .get(int idx), for example, it is easy to accidentally have the wrong method called. A simple example: public static void test(int x) { System.out.println("int: " + x); } public static void test(Integer x) { System.out.println("Integer: " + x); } public static void main(String[] args) { Integer x = new Integer(5); test(x); // should probably give a warning test((int) x); } I'm sure this is defined exactly in the language spec, but it creates the opportunity for programmer error, so it seems like a warning is in order.
Interesting usecase. One thing you can use is the compiler warning for autoboxing conversions. By not seeing the expected warning, you may hint that you are calling the wrong method ? Anyway, this is a nice suggestion.
(Pinging again on this old feature request...) A much more common case than the example I gave, and the source of many Java bugs, is the confusion of boxed and non-boxed methods in collections, e.g. List<Integer> x = Arrays.of(1, 2, 3, 4, 5); // Remove element at *index* 1: Integer y = x.remove(1); // y = x.remove((int) 1) => y = Integer(2), x = [1, 3, 4, 5] // Remove element with *value* Integer(2) (which is no longer in the list): Integer z = x.remove(y); // y = x.remove(Integer(2)) => z = null, x = [1, 3, 4, 5] Many problems can occur due to this ambiguity, for example if the declaration of y is changed from "Integer y" to "int y", to rely on auto-unboxing, then This completely changes the semantics of x.remove(y). I have two requests: (1) It would be great to have Eclipse show a warning on overloaded method calls that are not explicitly casted, and are therefore ambiguous according to the language spec, but are *functionally ambiguous* in the context of boxing and unboxing. (2) Also, "Source > Cleanup" should never remove unnecessary casts if the cast explicitly disambiguates method calls that differ only in whether parameters use primitive types or wrapper types (i.e. are "ambiguous" in the context of boxing/unboxing).
(Typo: "UNambiguous according to the language spec") -- I realize there is no ambiguity between List#remove(int) and List#remove(Integer) from the point of view of resolving which method to call -- these methods are only "functionally ambiguous" from a usage point of view, because boxing and unboxing happen automatically.
Luke, I agree, this is an interesting and useful proposal. But I doubt we have the resources to consider this, at least not for now. Copying Stephan and Manoj for weighing in.