• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

generic question

 
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I sometimes see

List<Integer> a = new ArrayList();

or

List a = new ArrayList<Integer>();

With one missing <> on either side.

What are the differences and implications? Please give example if you can. Thanks.
[ September 05, 2007: Message edited by: Tony Smith ]
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Case one:


The first line produces a warning.
Because variable a has a generic type List<Integer> and whatever you get out of the list is guaranteed to be an Integer. Therefore the third line will compile and the whole snipped would output a 1.

Why is it allowed to have the ArrayList non-generic here?
Because old classes compiled with java 4.1 or lower still have to work, and an old 4.1 class can easily have an ArrayList as return type.

Case two:


Here a is of raw type. It stores only objects and you can retrieve only objets from that collection. Even if the object is of type ArrayList<Integer>.
Therefore you get now a compiler error in the third line. Because the cast (Integer) is missing.
You have to insert it manually (in comparison to generics on both side, the compiler would do this for you behind the scenes).
And now the second line produces a warning. Compiler also would warn you if the first line were List a = new ArrayList(); (raw type on both sides).
Because only the compile type matters, and it is non-parameterized.
You can store anything into it. A line a.add("howdy"); in this context would compile also.
Again this "half-generics" is also allowed because it must be guarantied that generic and legacy code can interact.


Hope this helped so far,
Yours,
Bu.
 
No thanks. We have all the government we need. This tiny ad would like you to leave now:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic