简体   繁体   English

Java-ArrayList <>和LinkedList <>-类作为标识符

[英]Java - ArrayList<> and LinkedList<> - class as an identifier

https://imgur.com/nb6sjuK https://imgur.com/nb6sjuK

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 . 我不明白标识符在本示例中的作用,这是编程的新手,我意识到ArrayList<String>创建了字符串列表,并且与LinkedList<String>相同,但是当您按下类时会发生什么在标识符中,例如LinkedList<Song> -,而Song是一个类。 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. String是一个类,就像Song也是一个类。 It means that you can only insert objects of this class into your List . 这意味着您只能将此类的对象插入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 the identifier ? 但是,当您在identifier推送class时会发生什么?

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). 首先,这不是它的一个标识符Type ,这该是多么泛型工作,你传递一个Type之间的<>所以编译器知道预期的Type为这个泛型类(这里的集合)。 And Collections List , Set ... are good examples for Generics implementations. 并且Collections ListSet ...是泛型实现的好例子。

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 . 就像Song是一个类一样, String也是java.lang包中的预定义类,因此当您将一个类传递给集合时,编译器将期望此集合中的所有元素都属于此Type

For example in your code: 例如在您的代码中:

LinkedList<Song> playlist = new LinkedList<Song>();

All playlist items are expected to be instances of Song class. 所有playlist项均应为Song类的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM