Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify the type for ArrayList

In Java, and Android, I end up using ArrayList<String> for the supplying list as I find them easier to use than the standard String[]. My real questions though are this:

What is the <String> portion of the ArrayList<String> called?
How can I create classes and use the <> [modifier]? (I don't know what it's actually called, so for now it's modifier).

Thanks!

like image 588
Adam Avatar asked Mar 28 '13 14:03

Adam


People also ask

What is ArrayList types of array?

The ArrayList is a class of Java Collections framework. It contains popular classes like Vector, HashTable, and HashMap. Array is static in size. ArrayList is dynamic in size.

What data type is ArrayList?

ArrayList is a kind of List and List implements Collection interface. The Collection container expects only Objects data types and all the operations done in Collections, like iterations, can be performed only on Objects and not Primitive data types.

Can ArrayList be any type?

Java ArrayList is an ordered collection. It maintains the insertion order of the elements. You cannot create an ArrayList of primitive types like int , char etc. You need to use boxed types like Integer , Character , Boolean etc.

What is the default type of ArrayList?

ArrayLists have no default values. If you give the ArrayList a initialCapacity at initialization, you're just giving a hint for the size of the underlying array—but you can't actually access the values in the ArrayList until you add the items yourself. Save this answer.


2 Answers

Here, you wil maybe see clearer:

ArrayList<TypeOfYourClass>

You can create a Person class and pass it to an ArrayList as this snippet is showing:

ArrayList<Person> listOfPersons = new ArrayList<Person>();
like image 127
javadev Avatar answered Oct 02 '22 21:10

javadev


Supose you want an ArrayList to be filled only with Strings. If you write:

ArrayList<String> list = new ArrayList<String>();
    list.add("A");
    list.add("B");
    list.add("C");

You can be sure than if somebody tries to fill the arrayList with an int it will be detected in complile time.

So, generics are used in situations where you want enforce restrictions like this.

like image 36
joan Avatar answered Oct 02 '22 21:10

joan