How Objects Can an ArrayList Hold in Java?
Last Updated :
04 Oct, 2021
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.
Implementation:
- 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.
Example
Java
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
names.add( "Computer" );
names.add( "Science" );
names.add( "Portal" );
System.out.print(names);
}
}
|
Output
[Computer, Science, Portal]
B) Second half: Making the same ArrayList with class objects as elements.
Example
Java
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
Person p1 = new Person( "Aditya" , 19 );
Person p2 = new Person( "Shivam" , 19 );
Person p3 = new Person( "Anuj" , 15 );
ArrayList<Person> names = new ArrayList<Person>();
names.add(p1);
names.add(p2);
names.add(p3);
System.out.println(names.get( 0 ).name);
System.out.println(names.get( 0 ).age);
System.out.println(names.get( 1 ).name);
System.out.println(names.get( 1 ).age);
System.out.println(names.get( 2 ).name);
System.out.println(names.get( 2 ).age);
System.out.println();
System.out.println(
"Optional Part Added For Better Understanding" );
System.out.println(names);
}
}
class Person {
String name;
int age;
Person(String name, int age)
{
this .name = name;
this .age = age;
}
}
|
Output
Aditya
19
Shivam
19
Anuj
15
Optional Part Added For Better Understanding
[Person@214c265e, Person@448139f0, Person@7cca494b]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...