I don't get it what the identifier does in this example, I'm new with programming and what I realize is that ArrayList<String>
creates the list of Strings and same with LinkedList<String>
but what happens when you push a class in the identifier, like - LinkedList<Song>
- and Song
is a class . Thanks in advance.
public class Main {
private static ArrayList<Album> albums = new ArrayList<Album>();
LinkedList<Song> playlist = new LinkedList<Song>();
public static void main(String[] args) {
// write your code here
Album album = new Album("StormBringer" , "Deep Purple");
album.addSong("Stormbringer" , 4.6);
album.addSong("Love don't mean a thing" , 4.22);
String
is a class like Song
is also a class. It means that you can only insert objects of this class into your List
. Objects of other classes are not allowed to be added, because the type does not match. Trying to do so will result in a compile error. So your list is type save. This feature is called generics .
but what happens when you push a
class
in theidentifier
?
First of all it's not an identifier it's a Type
, and this is how Generics works, you pass a Type
between <>
, so the compiler knows the expected Type
for this Generic class (here the Collection). And Collections List
, Set
... are good examples for Generics implementations.
And like Song
is a class String
is also a predefined class in the java.lang
package, so when you pass a class to your collection, the compiler will expect that all the elements in this collection are of this Type
.
For example in your code:
LinkedList<Song> playlist = new LinkedList<Song>();
All playlist
items are expected to be instances of Song
class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.