To append an element to a list in Java, you can use the add
method of the ArrayList class or any class that implements the List interface.
In this example,
numbers
with initial integer values.add
method of the ArrayList numbers
to append a new integer to the list.add
method modifies the original list by adding the new element at the end.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
System.out.println("Updated list: " + numbers);
}
}
Updated list: [1, 2, 3, 4, 5]
In this example,
numbers
with initial integer values.add
method of the LinkedList numbers
to append a new integer to the list.add
method modifies the original list by adding the new element at the end.import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
System.out.println("Updated list: " + numbers);
}
}
Updated list: [1, 2, 3, 4, 5]
In this tutorial, we learned How to Append an Element to a List in Java language with well detailed examples.