What does this mean in ArrayList in Java

I am new to Java and I have seen an ArrayList example similar to this.

listing = new ArrayList<Lot>(); 

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

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

Can someone explain this to me?

thanks

+1
source share
4 answers

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

+4
source

It is called a type parameter. It means that ArrayList will contain only objects of type Lot Check out the 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 that should be noted in the above example, for example,

  • In eg(b) . Since we have already indicated that the ArrayList will contain only objects of the Lot, in Line 3 , we did not have to cast it to dial the Lot object. This is because the compiler already knows that it will only have an object of type Lot.
  • Attempting to add any other type of object to eg (b) will result in a compile-time error. This is because the compiler has already identified this list, which contains only elements of type Lot . This is called type checking
+4
source

This is an extension for a system such as Java, Generics .

Generics allows you to create a List that contains a specific subtype of Object (or a specific set of Object that implements certain interfaces, rather than a collection that contains only simple Object s.

0
source
 listing = new ArrayList<Lot>(); 

This line says that the type of objects that you want to insert, update, retrieve from or from an ArrayList are of type Lot. This is what is called generics in java.
Using generic type generation is not required when retrieving objects from any list.

0
source

Source: https://habr.com/ru/post/893473/


All Articles