List add/insert elements
In this chapter you will learn:
Add element to List
We can use the following methods to add elements to
a List. A good feature of List is that it grows as we insert element.
The two implementation of List interface have different ways to increase its size.
ArrayList
uses internal array to manage elements, while
LinkedList
uses doubly-linked list.
The add/insert methods are defined as follows:
boolean add(E e)
Appends to the end.void add(int index, E element)
Inserts at the specified position.boolean addAll(Collection<? extends E> c)
Appends all to the end.boolean addAll(int index, Collection<? extends E> c)
Inserts all at the specified position.
import java.util.ArrayList;
import java.util.List;
/*from j a v a2s .c o m*/
public class Main {
public static void main(String[] args) {
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("java2s.com");
System.out.println("List has:" + list);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections