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!
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.
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.
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.
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.
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>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With