How Objects Can an ArrayList Hold in Java?
ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java just as Vector in C++. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.
In order to understand the problem is divided into two halves:
- First Half: Representing generic addition of a normal element in the ArrayList. Data-type of the elements that are to be stored in the ArrayList is either String or Integer type.
- Second half: Making the same ArrayList with class objects as elements.
Syntax: Declaring List
ArrayList<String> names = new ArrayList<String>();
Here <String> represents the data-type of the elements that is to be stored in the ArrayList. Remember that this can not be any primitive data-type such as int or float.
Illustration: Sub Class taken for consideration is randomly named ‘Person’.
Method: List.get() method of List interface in Java is used to get the element present in this list at a given specific index.
- Make an auxiliary java class.
- Give it some properties. For example, class Person can include name, age, number, etc
- Create a new object.
- Store the above-created object inside the ArrayList.
- Print elements of above object created using List.get() method.
- Making a Person class object.
- Making an ArrayList with Person objects as elements.
(A) First Half: Representing generic addition of a normal element in the ArrayList.
[Computer, Science, Portal]
B) Second half: Making the same ArrayList with class objects as elements.
Aditya 19 Shivam 19 Anuj 15 Optional Part Added For Better Understanding [Person@214c265e, Person@448139f0, Person@7cca494b]