List<Integer> list0 = new List1<Integer>();
a) Is the word "List" a keyword in java??
b) When creating an object, shouldn't the name of the class be the same on both side? For example:
Point x = new Point(1,2)
c) What does the following code mean?
List<Integer> list0 = new List1<Integer>();
a) No, it isn't, it's an Interface
b) Not always. The type on the right has to be compatible with the one being assigned to - it must be the same, or a subtype. In this case List1
must implement the List
interface.
c) Create a new List1
instance to hold Integers ("integer" is wrong - it must be "Integer"); this is only legal if the List1
class implements the List
interface. The <Integer>
is a generic type that restricts the types that the collection (List) can hold.
List1
must be declared somewhere as
public class List1<T> implements List<T> {
...
List
is an interface, so objects of any class that implements List
can be assigned to a variable of type List
.
0) No. List
is the name of an Interface. See: http://docs.oracle.com/javase/6/docs/api/java/util/List.html
1) No. java has Polimorphism, so you can call an object by the name of one implemented Interface or an Extended Class
List是Java中的接口,您可能想将其实例化为ArrayList。
List list0 = new ArrayList();
C. Perhaps you mean
List l = new ArrayList<>();
This is a list that can contain only Integer types
List is not a keyword, it is a type, specifically, a Java interface. The code in your example doesn't compile (unless the List1
class is defined as: class List1 implements List { ... }
), however something like this would:
List<Integer> ls = new ArrayList<Integer>();
This creates an ArrayList
that can hold Integers
, and assigns a reference to it to the variable ls
, which is declared as the type List<Integer>
. ls
could potentially hold a reference to a different type of list, such as a LinkedList
, but you can guarantee that ls
does point to some sort of list (unless it's null) and therefore you can use the methods specified in the List
interface.
The type of the variable does not need to be the same as the type of the object on the right side of the assignment (though it often is), but the object must be either the same type, or a subclass/implementation of the variable type. Since all objects extend Object
you can always do something like:
Object obj = new ArrayList<Integer>();
Though, like above, the only methods you have access to from obj
are what's defined in Object
, even though the object being referred to is actually an ArrayList
.
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.