简体   繁体   中英

Creating a LinkedList

If I create a LinkedList like this:

LinkedList<Integer> Mistery = new LinkedList<>();

It will be possible to implement this: Mistery.getFirst();

If, on the other hand, I create a LinkedList like this:

List<Integer> Mistery = new LinkedList<>();

It won't be possible to implement the getFirst() method on the Mistery list.

Why?

因为您将Mistery声明为超级类型: List (尽管您选择了LinkedList作为实现),所以在List接口中没有定义getFirst()方法。

List<Integer> Mistery = new LinkedList<>();

By declaring the variable this way, you're telling the compiler: I want to use a List. The implementation of the List I want is LinkedList, but the rest of the code shouldn't know about that. All it needs to know is that it's a List. I might change my mind later and use an ArrayList, and the rest of the code would still compile, because ArrayList is also a List. I could also assign another object to the same variable, and this object might be of type ArrayList, or CopyOnWriteArrayList, or any other type of List.

Since List doesn't have a getFirst() method, you can't use it: the variable is of type List, not LinkedList. At runtime, sure, the object is of type LinkedList. But the compiler only knows the type of the variable. It doesn't know its concrete type at runtime.

Side note: Java variables should start with a lowercase letter, to respect the standard conventions.

Something to think about is also why you would want to use List. (Answers already covering why List doesn't have getFirst() method).

Say you have a method that prints content of a list:

public printStuff(List list){
   for(Object element: list){
       System.out.println(element);}

By declaring your Mistery list a List it means you could then (through polymorphism ), use a single method for a range of lists ie

List<Integer> Mistery = new LinkedList<>();
List<Integer> Mistery2 = new ArrayList<>();
List<String> Mistery3 = new ArrayList<>();
//etc

Then you can do this:

printStuff(Mistery);
printStuff(Mistery2);
printStuff(Mistery3); //can even print out a List which contains Strings

If the List was declared like this LinkedList<Integer> Mistery = new LinkedList<>(); you could not use the method printStuff . You should also read up on casting .

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.

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