Lists  (in java.util)


A List is a collection construct, that is by definition an ordered collection, also known as a sequence.  Unlike the array, the number of the elements in the List can be reduced or enlarged.
A Java List collection can only hold objects. 
List is an interface, so it can't be  instantiated directly. There are two general-purpose List implementations — ArrayList and LinkedList.  The most commonly used implementation, is ArrayList. It offers constant-time positional access, and it can take advantage to move multiple elements at the same time.
     
            List<Object> listOfObjects = new ArrayList<Object>();   //empty list with an initial capacity of ten

           
List<Object> listOfObjects2 = new ArrayList<Object>(listOfObjects);   //copy constructor - new List with all elements from  listOfObjects

Formal type
The <Object> in the above code is called the formal type, and it tells the compiler that this List contains a collection of type Object (the super class of all java classes), which means that the List can hold any kind of object.

It is possible to tighten up the constraints on what could or could not go into the List:

        class Person{
            ...
        }
        class Student extends Person{
            ...
        }
        List<Person> listOfPersons = new ArrayList<Person>();

Now the  List can only hold Person instances (and all instances from its derived classes - like Student).

Using Lists

Put something in the List
                    Remark: E - the type of elements in this list

Ask the List how big it currently is.
Acessing an element in the List
Get something out of the List.
Creating a sub List.
Put multiple elements  from an existing List. More information about ArrayList.


Example:
import java.util.*;
public class ListDemo {
    public static void main(String args[]) {
        // Create an array list
        ArrayList <String>  al = new ArrayList <String>();
        System.out.println("initial size:"+al.size());
        // add elements to the array list
        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");
        System.out.println("the new size:"+al.size());
        for(int i = 0; i <al.size(); i++){
            System.out.print(al.get(i)+" ");
        }
        System.out.println();
        String ex = al.remove (2);
        System.out.println("removing value:"+ex);
        System.out.println("size after remove:"+al.size());
        for(String s : al){
            System.out.print(s+ " ");
        }
        System.out.println();
        //    copy all elements in new ArrayList
        //     1.Using copy constructor
        ArrayList <String> sec = new ArrayList <String>(al);
        System.out.println("\tsec size: "+sec.size());
        for(String s : sec){
            System.out.print(s+ " ");
        }
        System.out.println();
        //      2. Using method addAll()
        sec.clear();
        System.out.println("\tsec size after clear(): "+sec.size());
        sec.addAll(al);
        System.out.println("\t\tsec size after addAll(): "+sec.size());
        for(String s : sec){
            System.out.print(s+ " ");
        }
        System.out.println();
        // Add just a portion of the second ArrayList
        sec.clear();
        sec.addAll(al.subList(1, 4));
        System.out.println("\t\tsec size after add subList(1,4): "+sec.size());
        for(String s : sec){
            System.out.print(s+ " ");
        }
        System.out.println();
    }
}

initial size:0
the new size:6
C A E B D F
removing value:E
size after remove:5
C A B D F
    sec size: 5
C A B D F
    sec size after clear(): 0
        sec size after addAll(): 5
C A B D F
        sec size after add subList(1,4): 3
A B D



The same example with Integer elements (
cannot hold primitive data)
import java.util.*;
public class ListDemo1 {
    public static void main(String args[]) {
        // Create an array list
        ArrayList <Integer>  al = new ArrayList <Integer>();
        System.out.println("initial size:"+al.size());
        // add elements to the array list
        al.add(10);
        al.add(20);
        al.add(30);
        al.add(40);
        al.add(50);
        al.add(60);
        System.out.println("the new size:"+al.size());
        for(int i = 0; i <al.size(); i++){
            System.out.print(al.get(i)+" ");
        }
        System.out.println();
        Integer ex = al.remove (2);
        System.out.println("removing value:"+ex);
        System.out.println("size after remove:"+al.size());
        for(Integer s : al){
            System.out.print(s+ " ");
        }
        System.out.println();
        //    copy all elements in new ArrayList
        //     1.Using copy constructor
        ArrayList <Integer> sec = new ArrayList <Integer>(al);
        System.out.println("\tsec size: "+sec.size());
        for(Integer s : sec){
            System.out.print(s+ " ");
        }
        System.out.println();
        //      2. Using method addAll()
        sec.clear();
        System.out.println("\tsec size after clear(): "+sec.size());
        sec.addAll(al);
        System.out.println("\t\tsec size after addAll(): "+sec.size());
        for(Integer s : sec){
            System.out.print(s+ " ");
        }
        System.out.println();
        // Add just a portion of the second ArrayList
        sec.clear();
        sec.addAll(al.subList(1, 4));
        System.out.println("\t\tsec size after add subList(1,4): "+sec.size());
        for(Integer s : sec){
            System.out.print(s+ " ");
        }
        System.out.println();
    }
}
initial size:0
the new size:6
10 20 30 40 50 60
removing value:30
size after remove:5
10 20 40 50 60
    sec size: 5
10 20 40 50 60
    sec size after clear(): 0
        sec size after addAll(): 5
10 20 40 50 60
        sec size after add subList(1,4): 3
20 40 50






Iterating over a List


 An iterator is an object that enables a programmer to traverse a collection. The Iterator returned by List's iterator() operation returns the elements of the list in proper sequence.
Creating
    Iterator<Type> it = list.iterator();

List also provides a richer  iterator, called a ListIterator, which allows you to traverse the List in either direction, modify the List during iteration, and obtain the current position of the iterator.
Creating
        ListIterator<Type> it = list.listIterator();
        ListIterator<Type> it = list.listIterator(int)   

The List  has two forms of the listIterator method. The form with no arguments returns a ListIterator positioned at the beginning of the list; the form with an int argument returns a ListIterator positioned at the specified index. The index refers to the element that would be returned by an initial call to next. An initial call to previous would return the element whose index was index-1. In a list of length n, there are n+1 valid values for index, from 0 to n, inclusive.

Intuitively speaking, the cursor is always between two elements — the one that would be returned by a call to previous and the one that would be returned by a call to next. The n+1 valid index values correspond to the n+1 gaps between elements, from the gap before the first element to the gap after the last one. The following figure shows the five possible cursor positions in a list containing four elements.


Examples

import java.util.*;
public class IteratorDem {
    public static void main(String arg[]){
        // Create an array list
          ArrayList <String>  al = new ArrayList <String>();
          // add elements to the array list
          al.add("C");
          al.add("A");
          System.out.println("ArrayList:"+al.get(0)+" "+al.get(1));
         
          ListIterator<String> litr = al.listIterator();
         // litr.set("new");             error- there is no element in the iterator
         
         
          System.out.println("before element "+litr.nextIndex());
          System.out.println("after element "+litr.previousIndex());
         
          System.out.println(litr.next());
          System.out.println("before element "+litr.nextIndex());
          System.out.println("after element "+litr.previousIndex());
         
          litr.set("modified");     // modify the last element returned
                                          // by next() or previous()
          System.out.println("ArrayList:"+al.get(0)+" "+al.get(1));
         
    }
}
ArrayList:C A
before element 0
after element -1
C
before element 1
after element 0
ArrayList:modified A


import java.util.*;
public class IteratorDemo {
   public static void main(String args[]) {
      // Create an array list
      ArrayList <String>  al = new ArrayList <String>();
      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");

      // Use iterator to display contents of al
      System.out.print("Original contents of al: ");
      Iterator<String> itr = al.iterator();
      while(itr.hasNext()) {
         System.out.print(itr.next() + " ");
      }
      System.out.println();
     
      // Modify objects being iterated
      ListIterator<String> litr = al.listIterator();
      while(litr.hasNext()) {
         litr.set(litr.next() + "+");
      }
      System.out.print("Modified contents of al: ");
      itr = al.iterator();
      while(itr.hasNext()) {
         System.out.print(itr.next() + " ");
      }
      System.out.println();

      // Now, display the list backwards
      System.out.print("Modified list backwards: ");
      while(litr.hasPrevious()) {
         System.out.print(litr.previous() + " ");
       }
       System.out.println();
    }
}
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+