• Post Reply Bookmark Topic Watch Topic
  • New Topic

Learning Generics  RSS feed

 
Elim Banda
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from headfirst java page pg. 541 please see attachments.

I dont understand what they mean assigning variables of generic type. In the case of ArrayList<song> what is a variable. Also please explain the code with a question mark to me.

I thought variables where like instance variables like say a dog of a certain hieght and weight. a piece of pie for the best explanation.
Capture1.PNG
[Thumbnail for Capture1.PNG]
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, in the piece of code with the question mark, songList is a variable, and its type is generic, namely List<Song>.

A variable is just a name for a piece of memory that holds some data. songList is a name for a piece of memory that holds a reference to a list of songs.
 
Knute Snortum
Sheriff
Posts: 4287
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This sets a variable songList of type List<Song>.  Let's break that down.

Why List and not ArrayList?

Because you want to code to the interface rather than the implementation.  Here List is the interface and ArrayList is the implementation.

Why List<Song> and not just List?

A variable of type List can hold any type of data.  This isn't safe programming, though.  If you want the elements in the list to all be the same type, you have to use generics.  List<Song> specifies that every element must be a Song.

Why new ArrayList<Song>()?

The new keyword creates a new object.  The reference it returns needs to be of a type or subtype of the variable type.  ArrayList<Song> is a subtype of List<Song> since it is an implementation of the interface.
 
Elim Banda
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks knute but what does this line mean please explain. " you want to code to the interface rather than the implementation. "
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It means that you should use the least specific type you can use to make your application work. Let's say that you require the get() method. You would then use a variable of type List. If you only need to see if a collection contains a certain element, or add a new element to the end, then you would use Collection instead of List. If all you need to do is iterate over all elements in a collection, you would use Iterable instead of Collection.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!