Java Reference
In-Depth Information
Now the List will look as shown in Figure 12-4 .
Index >>
0
1
Sara
2
3
4
Element >>
John
Richard
Donna
Ken
Figure 12-4. The resulting List after a new element is added at index 1 in the List in Figure 12-3
note that a List does not allow inserting an element at any arbitrary index by using the add(int index,
E element) method. if the List is empty, you can use only 0 as the index to add the first element to the list. if you have five
elements in a List , you must use indexes between 0 and 5 to add a new element to the List . the index from 0 to 4
will insert an element between existing elements. the index of 5 will append the element to the end of the List . this
implies that a List must grow sequentially. You cannot have a sparse List such as a List with first element and tenth
element, leaving second to ninth elements non-populated. this is the reason that a List is also known as a sequence .
Tip
Listing 12-13 demonstrates how to use a List . It shows how to add, remove, and iterate over its elements
using indexes.
Listing 12-13. Using a List with the ArrayList as Its Implementation
// ListTest.java
package com.jdojo.collections;
import java.util.List;
import java.util.ArrayList;
public class ListTest {
public static void main(String[] args) {
// Create a List and add few elements
List<String> list = new ArrayList<>();
list.add("John");
list.add("Richard");
list.add("Donna");
list.add("Ken");
System.out.println("List: " + list);
int count = list.size();
System.out.println("Size of List: " + count);
// Print each element with its index
for(int i = 0; i < count; i++) {
String element = list.get(i);
System.out.println("Index=" + i + ", Element=" + element);
}
List<String> subList = list.subList(1, 3);
System.out.println("Sub List 1 to 3(excluded): " + subList);
 
Search WWH ::




Custom Search