Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Collection class of Java 5

 
michael yeung
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java 5, we can initialize the object of collection class like the following:

List<String> list = new ArrayList<String>();

Does the coding <String> mean we should add only String object into the List?

Thanks!!!
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup. It does two nice things for you. It prevents you from adding anything but a String with compile time checking, and it lets you eliminate casting when you take your Strings back out. Sweeeet.
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

It prevents you from adding anything but a String with compile time checking, and it lets you eliminate casting when you take your Strings back out

And if you declare the object as Object, it just simply goes back to the original style that you could add anything to a list.

Nick
 
somkiat puisungnoen
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by michael yeung:
In Java 5, we can initialize the object of collection class like the following:

List<String> list = new ArrayList<String>();

Does the coding <String> mean we should add only String object into the List?

Thanks!!!


yes,

you can add type class and subclass.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FYI, this question fits under the broader scope of Generics, which is a new feature in Tiger. If you are interested in learning more about how these work, just google for it or use the Search tool here at the Ranch. This topic has been discussed a lot lately with the advent of Java 5.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic