10

I wrote a simple program using generic type. However, the simple example behaves differently on different JDK versions.

Simple code is as follows:

import java.util.List;

public class GenericTypes {

public static String method(List<String> list) {
    System.out.println("Method method(List<String> list) is invoked.");
    return "";
}

public static int method(List<Integer> list) {
    System.out.println("Method method(List<Integer> list) is invoked.");
    return 0;
}

}

Scenario#1 ==> on JDK 1.7, Compile error appears

enter image description here

`Method method(List<String>) has the same erasure method(List<E>) as another method in type GenericTypes.`

Scenario#2 ==> on JDK 1.6 or 1.5, there is no Compile error.

Screenshot for the code and output in console is as follows:

enter image description here

As we know, Generic Type is introduced since JDK 1.5. However, with the above simple example, it behaves differently in different JDK versions.

Here is my questions:

Q1==> What change has been made in higher JDK version (like JDK 1.7) to make Generic Type behaviors differently in some scenarios, such as the above simple example?

Q2==> Is compile error better than no compile error in above example?

Please help me out with this. Thank you very much in advance.

Mengjun
  • 3,159
  • 1
  • 15
  • 21
  • +1 Doesn't this also imply type erasure had increased in Java 7 and backwards compatibility broke? – nanofarad Nov 28 '13 at 14:49
  • 5
    How come in JDK 7 you return `int` and in 6 you return `Integer` ? – ryvantage Nov 28 '13 at 14:49
  • Are you using the same IDE for both images? I got warnings with Java 6 and Eclipse, bet I could make it a error changing a setting. – Jonathan Drapeau Nov 28 '13 at 14:50
  • 6
    See [similar question](http://stackoverflow.com/questions/18613562/jdk-1-7-breaks-backward-compatibility-generics) – Alexey Odintsov Nov 28 '13 at 14:50
  • @ryvantage - This should be a typo. I change it from int to Integer, compile error is still there. – Mengjun Nov 28 '13 at 15:04
  • @Jonathan Drapeau - Different IDEs are used. Eclipse-Galileo is used for JDK 1.6. Eclipse-Kepler is used for JDK 1.7 – Mengjun Nov 28 '13 at 15:06
  • Please see this discussion - http://stackoverflow.com/questions/1998544/method-has-the-same-erasure-as-another-method-in-type And this link - http://joshbranchaud.com/blog/2013/05/26/Javas-Type-Erasure.html – TR1 Nov 28 '13 at 17:12
  • Java7 changed spec and made the program illegal. It's wrong to say it's a bug fix. Your overloading methods are very reasonable, and ideally the language should be able to support it. – ZhongYu Nov 28 '13 at 17:56
  • Java has pretty much given up strict backward compatibility. The language is too complex, it's impossible to move ahead without breaking some existing code. that's especially true for the upcoming Java8 – ZhongYu Nov 28 '13 at 17:58
  • @zhong.j.yu - Thanks for the information. I agree with you. :) – Mengjun Nov 29 '13 at 01:35

0 Answers0