ArrayList Methods
Learn the basic ArrayList methods.
This section lists some common methods of an ArrayList
class. We’ll cover them one by one in detail.
Add items
Variation I
We use the add(E e)
method to add elements to the ArrayList
. It takes an element, e
, of E
type, appends it to the end of the list, and returns true
.
import java.util.ArrayList;class AddItems{public static void main(String args[]){ArrayList<String> students = new ArrayList<String>(); // empty list// Adding elementsstudents.add("James");students.add("Allen");System.out.println(students);}}
Initially, we create an empty ArrayList
with the name, students
. Look at line 10. We call the add()
method on students
and send James as an argument. Likewise, we add Allen in the next line. Later, at line 13, we print the list and get the output: [James, Allen].
Variation II
We use the add(int index, E e)
method to insert the specified element, e
, at the specified position, index
, in a list. It’s a void
method.
import java.util.ArrayList;class AddItems{public static void main(String args[]){ArrayList<String> students = new ArrayList<String>(); // empty list// Adding elementsstudents.add(0, "James");students.add(1, "Allen");System.out.println(students);students.add(0, "Kim");System.out.println(students);}}
Initially, we create an empty ArrayList
with the name: students
. Look at line 10. We call the add()
method on students
and send , and James as arguments. Likewise, we add Allen at the ...
Get hands-on with 1400+ tech skills courses.