0

I was trying to explore Java Generics and when I tried below code, I was expecting, line 3 will compile fine, but line 4 will show compilation error.

1|  PriorityQueue queue1 = null;
2|  PriorityQueue<Integer> queue2 = null;
3|  queue1 = queue2;
4|  queue2 = queue1;

However to my surprise, line 4 is compiling fine. I am cunfused at this point, why this is allowed. Because queue2 is allowed to hold only Integer. So is it okay to assign queue1 as it can hold value of any type? Considering a code written before java 5.0, I can understand line 3, not line 4.

1|  PriorityQueue<?> queue1 = null;
2|  PriorityQueue<Integer> queue2 = null;
3|  queue1 = queue2;
4|  queue2 = queue1;

For above code, I am getting expected result, which is, getting compilation error for line 4.

Can someone please explain the above behavior?

Kartic
  • 2,935
  • 5
  • 22
  • 43
  • Can you explain why it shouldn't compile esp as you might have code which was written before Java 5.0? – Peter Lawrey May 31 '16 at 09:11
  • Updated my question a little bit. – Kartic May 31 '16 at 09:21
  • 1
    Consider you have some code which uses RawTypes and it is calling some code which now has generics. e.g. it used to have a method `add(PriorityQueue)` and now it has `add(PriorirtyQueue)` would you expect this to break backward compatibility or produce a warning? – Peter Lawrey May 31 '16 at 09:28
  • Okay, in this case it should produce an warning and it would be developers responsibility to ensure that the elements are Integers, not compiler. Does it answer your and my question? – Kartic May 31 '16 at 09:39
  • 1
    So indeed, it should produce a warning. i.e. this is for backward compatibility with code which was written without generic types. What they could have done is only allow this for parameters, but not local assignments.... – Peter Lawrey May 31 '16 at 09:41
  • I think I got it. Thank you. You can post your comments as an answer so that I can accept it as an answer. – Kartic May 31 '16 at 09:51

0 Answers0