Java Add Elements to an ArrayList

ww‮.w‬lautturi.com
Java Add Elements to an ArrayList

To add elements to an ArrayList in Java, you can use the add method of the ArrayList class.

The add method adds a new element to the end of the ArrayList, and it takes a single argument that specifies the value of the element to be added.

Here is an example of how you can add elements to an ArrayList in Java:

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    // Create an ArrayList
    ArrayList<String> list = new ArrayList<>();

    // Add some elements to the ArrayList
    list.add("Apple");
    list.add("Banana");
    list.add("Orange");

    // Print the ArrayList
    System.out.println(list);  // Output: [Apple, Banana, Orange]
  }
}

In this example, the list variable is an ArrayList that stores strings.

The add method is used to add three elements to the ArrayList: "Apple", "Banana", and "Orange".

Then, the list variable is printed, and it contains the three elements that were added to the ArrayList.

It is important to note that the add method adds the element to the end of the ArrayList, and it always returns true.

Therefore, you can use the add method to append elements to the ArrayList, but you cannot use it to insert elements at a specific position in the ArrayList.

To insert an element at a specific position in an ArrayList, you can use the add method of the List interface, which takes two arguments: the index at which the element is to be inserted, and the element to be inserted.

Here is an example of how you can insert an element at a specific position in an ArrayList:

list.add(1, "Peach");

In this example, the element "Peach" is inserted at the index 1, which is the second position in the ArrayList.

After this operation, the ArrayList contains the following elements: "Apple", "Peach", "Banana", "Orange".

It is also possible to add multiple elements to an ArrayList using the addAll method of the ArrayList class.

The addAll method takes a collection as an argument, and it adds all the elements of the collection to the ArrayList.

Here is an example of how you can add multiple elements to an ArrayList using the addAll method:

import java.util.Arrays;
import java.util.List;

List<String> fruits = Arrays.asList("Mango", "Pineapple", "Grapefruit");
list.addAll(fruits);

In this example, the fruits variable is a List that contains three elements: "Mango", "Pineapple", and "Grapefruit".

The addAll method adds all the elements of the fruits list to the listArrayList.

After this operation, the ArrayList contains the following elements: "Apple", "Peach", "Banana", "Orange", "Mango", "Pineapple".

Created Time:2017-11-01 22:29:44  Author:lautturi