1. Using String elements
2. Using Integer elements
3. Using Custom Object
Read Also: How to iterate or loop over ArrayList in Java
Let's dive deep into the topic:
How to add an element to ArrayList in Java
1. Using boolean add(Object element) method
The method signature of add method is: public boolean add(Object element)
1.1 Add String elements to the ArrayList Object
In the below example, we will create an empty ArrayList. Then add String elements to it using ArrayList.add() method.
import java.util.*;
public class AddMethodExample {
public static void main(String args[]) {
//Declaration of String ArrayList
ArrayList<String> arrlist = new ArrayList<String>();
//Example of add method for String ArrayList
arrlist.add("California");
arrlist.add("New York");
arrlist.add("Boston");
arrlist.add("San jose");
arrlist.add("San Francisco");
System.out.println("ArrayList Elements of String Type: "+ arrlist);
}
}
Output:
ArrayList Elements of String Type: [California, New York, Boston, San jose, San Francisco]
1.2 Add Integer elements to the ArrayList Object
In the below example, we will create an empty ArrayList and then add Integer elements to it using the ArrayList.add() method.
import java.util.*;
public class AddMethodExample2 {
public static void main(String args[]) {
//Declaration of Integer ArrayList
ArrayList<Integer> arrlist2 = new ArrayList<Integer>();
//Example of add method for Integer ArrayList
arrlist2.add(12);
arrlist2.add(3);
arrlist2.add(9);
arrlist2.add(96);
arrlist2.add(8);
System.out.println("ArrayList Elements of Integer Type: "+arrlist2);
}
}
Output:
ArrayList Elements of Integer Type: [12, 3, 9, 96, 8]
1.3 Add Custom Object to the ArrayList
In the below example, we will create an ArrayList of Mobile objects and add Mobile objects to the list.
import java.util.*;
public class AddMethodExample3 {
public static void main(String args[]) {
//Declaration of ArrayList of Mobile objects
ArrayList<Mobile> mobiles = new ArrayList<>();
//Example of add method for ArrayList of Mobile objects
mobiles.add(new Mobile("Apple","iPhone"));
mobiles.add(new Mobile("Samsung","Galaxy S"));
mobiles.add(new Mobile("Xiaomi","Note Pro"));
// Displaying Mobile company and model
for(Mobile mobile: mobiles) {
mobile.printMobiles();
}
}
}
class Mobile {
public String company;
public String model;
// Constructor
public Mobile(String company, String model) {
this.company = company;
this.model = model;
}
public void printMobiles() {
System.out.println(company + " produces " + model);
}
}
Output:
Apple produces iPhone
Samsung produces Galaxy S
Xiaomi produces Note Pro
That's all for today. Please mention in the comments if you have any questions related to how to add an element or object to ArrayList in Java.
Reference:
ArrayList add(E e) method