Java ArrayList add, insert Example

This Java example uses the add method on ArrayList to add elements at the end. It uses add with an index to insert elements.
Add. This method appends an element to the end of an ArrayList. Add must be passed an element of the ArrayList's type, like String or Integer.
With two arguments, we can insert an element with add(). There is no insert method. We must specify a valid insertion index as the first argument to add().
First example. This program uses add() with one argument, and then with two arguments. We first append strings with values "cat" and "dog" to the end of the ArrayList.

Then: We invoke add() with two arguments. The first argument is 0. This means we want to insert "bird" at the first index.

Java program that uses add, add with index import java.util.ArrayList; public class Program { public static void main(String[] args) { // Create an ArrayList and add two strings. ArrayList<String> list = new ArrayList<>(); list.add("cat"); list.add("dog"); System.out.println(list); // Add a String at index 0. // ... This shifts the following elements to make room. list.add(0, "bird"); System.out.println(list); } } Output [cat, dog] [bird, cat, dog]
Add class instances. Here is an example of adding class instances to an ArrayList. With ArrayList we can specify built-in classes like String or Integer, but custom classes too can be used.

Animal: Here we use an Animal class with two fields (weight and color) and provide an Animal constructor.

Constructors

Add: We add three new Animals to the ArrayList. We create Animal instances pass them to add. Then we print the elements.

Java program that adds class instances to ArrayList import java.util.ArrayList; class Animal { public int weight; public String color; public Animal(int weight, String color) { // Create new Animal instance. this.weight = weight; this.color = color; } } public class Program { public static void main(String[] args) { // Create an ArrayList of custom objects. ArrayList<Animal> list = new ArrayList<>(); // Add new objects to the ArrayList. list.add(new Animal(10, "white")); list.add(new Animal(5, "orange")); list.add(new Animal(8, "grey")); // Display elements in our list. for (Animal animal : list) { System.out.println(animal.getClass().getName() + "/" + animal.weight + "/" + animal.color); } } } Output Animal/10/white Animal/5/orange Animal/8/grey
A summary. With add() we have both an "append" and an "insert" method on ArrayList. With an index argument, we can insert anywhere in an ArrayList. No other insert method is present.ArrayList addAll
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls