I have the following test class that uses generics to overload a method. It works when compiled with javac and fails to compile in Eclipse Helios. My java version is 1.6.0_2
After some research, I have the answer:
The code, as it is specified above should NOT compile. ArrayList<String>
and ArrayList<Integer>
, at runtime is still ArrayList
. But your code is not working because the returning type. If you set the same returning types for both methods, javac won't compile that...
I read that there is a bug in Java 1.6 (that is already fixed in Java 1.7) about this error. Is all about returning types... so, you will need to change the signature of your methods.
There is the bug 6182950 in Oracle's Bug Database.
This code is correct, as described in JLS 15.12.2.5 Choosing the Most Specific Method.
Also, consider coding to the interface:
List<String> ss = new ArrayList<String>();
List<Integer> is = new ArrayList<Integer>();
// etc.
As @McDowell notes, the modified method signatures appear in the class file:
$ javap build/classes/Test
Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
public static void main(java.lang.String[]);
public java.lang.String getFirst(java.util.ArrayList);
public java.lang.Integer getFirst(java.util.ArrayList);
}
Note that this does not contradict @meriton's observation about the class file. For example, the output of this fragment
Method[] methods = Test.class.getDeclaredMethods();
for (Method m : methods) {
System.out.println(Arrays.toString(m.getGenericParameterTypes()));
}
shows the formal parameter of main()
, as well as the two generic type parameters:
[class [Ljava.lang.String;]
[java.util.ArrayList<java.lang.String>]
[java.util.ArrayList<java.lang.Integer>]