开发者

what is this mean in the ArrayList in Java

I'm new in Java, and I have seen a ArrayList example like this.

  listing = new ArrayList<Lot>();
开发者_开发百科

I know that if I want to create an empty array list. Then I will use ArrayList()

But I don't understand what is the <Lot> between the "ArrayList" and "()".

Can someone explain it to me?

Thanks


This is Java Generics. The <Lot> indicates that the ArrayList will contain only objects of type Lot. It is useful because the compiler can do type checking on your ArrayList.


It is called as type parameter. It denotes that ArrayList will only contain objects of type Lot Check out concept of Generics.

You will get the use of this ArrayList<Lot> with this example :

// (a)Without Generics ....   
List myIntList = new ArrayList();                  // 1
myIntList.add(new Lot(0));                         // 2
Lot x = (Lot) myIntList.iterator().next();         // 3 


// (b)With Generics ....
List<Lot> myIntList = new ArrayList<Lot>();        // 1’
myIntList.add(new Lot(0));                         // 2’
Lot x = myIntList.iterator().next();               // 3  

Two points to be noted in the above e.g

  1. In e.g(b), Since we already specified that ArrayList will contain only objects of type Lot, in Line 3, we didn't have to perform casting it to type object Lot. This is because the compiler already know that it will have only Lot type of objects.
  2. Trying to add any other type of object to e.g (b) will result in compile time error. This is because the compiler has already identified this List is specific to contain elements of only type Lot. This is called type checking


It is an extension to Java's type system called, Generics.

Generics allow you to create a List that contains a specific sub-type of Objects (or a specific set of Objects that implement particular interfaces, instead of a collection that only holds plain Objects.


listing = new ArrayList<Lot>();

this line just says that the type of objects to be inserted,updated,retrieved in or from ArrayList are of the type Lot. This is what is called the generics in java.
Using the generics type casting is not required at the time of retrieval of objects from any List.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜