1

Something weird i've just realized:

Java documentation states that List collection has a method T get(int index) ... as you see the method returns T

However i can do:

List<Integer> l1 = new ArrayList<>();
l1.add(1);
List l2 = l1;
l2.add("Hello my friend");
Object o2 = l1.get(1);
System.out.println(o2);

And the result is "Hello my friend" !! ... this does not comply with stated in documentation since the result shall be Integer!

Is there any other possible explanaition?

Rafael
  • 2,521
  • 2
  • 33
  • 59
  • See also [*'What is a raw type and why shouldn't we use it?'*](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Radiodef Apr 09 '14 at 18:31

3 Answers3

3

Generics are compile-time checks. All bets are off once you start using raw types...which you are. This is why raw types are dangerous, and should never be used in new code.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • The only reason this even behaves as expected is because every object provides a ``toString`` method, and that is what was called. Anything that was specific to the type would have failed. – aruisdante Apr 09 '14 at 18:36
  • Thanks for your thoughs ... i, more or less, understand what is happening underneath. The Real collection is made of Objects and generics are compile-time checks as Louis states ... but my point is that i have a contract in List l1 with Integer get(int index) that is not being fulfilled in my opinion ... i wonder if you see different. – Rafael Apr 09 '14 at 19:53
  • The implementation of generics only checks that the return is of type Integer if you actually assign it to an Integer variable. – Louis Wasserman Apr 09 '14 at 20:01
1

List l2 is not generic, therefore it's basically a List<Object>, and when you use a non-generic list everything added to it becomes an Object and it's up to you to use them correctly, or you'll get ClassCastExceptions.

MrLore
  • 3,759
  • 2
  • 28
  • 36
  • Yes ... but l1 is List and i am using get method of l1 ... acording documentation it shall return Integer object ... and it does not. I can understand the underlying reasons ... but i mean ... is the documentation wrong? ... because it looks like that to me – Rafael Apr 09 '14 at 19:49
0

If you had declared l2 as a generic, then you would have gotten get a compile-time error (if your compiler is configured to complain about these things).

final List<Integer> l2 = l1;
cybersam
  • 63,203
  • 6
  • 53
  • 76