Creating an ArrayList with Multiple Object Types in Java
ArrayList class Java is basically a resizable array i.e. it can grow and shrink in size dynamically according to the values that we add to it. It is present in java.util package.
Syntax: To create an ArrayList of Integer type is mentioned below.
List<Integer> list = new ArrayList <Integer>();
It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types.
We will discuss how we can use the Object class to create an ArrayList.
Object class is the root of the class hierarchy. It is being extended by every class in Java either directly or indirectly. If a class doesn’t inherit from any other class then it extends the Object class directly otherwise if it extends any class then it extends the Object class indirectly from its base class. We can use the Object class to declare our ArrayList using the syntax mentioned below.
ArrayList<Object> list = new ArrayList<Object>();
The above list can hold values of any type. The code given below presents an example of the ArrayList with the Objects of multiple types.
Java
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
ArrayList<Object> arr = new ArrayList<Object>();
arr.add( "GeeksForGeeks" );
arr.add( 14 );
arr.add(1800L);
arr.add( 6 .0D);
arr.add( 1 .99F);
System.out.print(
"ArrayList after all insertions: " );
display(arr);
arr.set( 0 , 50 );
arr.set( 1 , 10 .0D);
System.out.print( "ArrayList after modifications: " );
display(arr);
}
public static void display(ArrayList<Object> arr)
{
for ( int i = 0 ; i < arr.size(); i++) {
System.out.print(arr.get(i) + " " );
}
System.out.println();
}
}
|
Output
ArrayList after all insertions: GeeksForGeeks 14 1800 6.0 1.99
ArrayList after modifications: 50 10.0 1800 6.0 1.99
Last Updated :
22 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...