Lists

A List is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.

Creating List Objects

Different types of lists can be created in different ways:

List a = new ArrayList();
List b = new LinkedList();

Type-safe Lists can be defined in the following way:

List<Obj> list = new ArrayList<Obj> ();
List<Integer> list = new ArrayList<Integer> (); // creates an integer list

Operations on Lists

In addition to the operations of Collections, Lists also allow add, remove, get and set operations based on numerical positions of elements in List. List provides following methods for these operations:

  • void add(int index, Object o): This method adds given element at specified index.
  • boolean addAll(int index, Collection c): This method adds all elements from specified collection to list. First element gets inserted at given index. If there is already an element at that position, that element and other subsequent elements(if any) are shifted to the right by increasing their index.
  • Object remove(int index): This method removes an element from the specified index. It shifts subsequent elements(if any) to left and decreases their indexes by 1.
  • Object get(int index): This method returns element at the specified index.
  • Object set(int index, Object new): This method replaces element at given index with new element. This function returns the element which was just replaced by new element.

Working with Lists

The following java program demonstrates positional access:

// Creating a list 
List<Integer> l1 = new ArrayList<Integer>(); 
l1.add(0, 1);  // adds 1 at 0 index 
l1.add(1, 2);  // adds 2 at 1 index 
System.out.println(l1);  // [1, 2] 

// Creating another list 
List<Integer> l2 = new ArrayList<Integer>(); 
l2.add(1); 
l2.add(2); 
l2.add(3); 

// Will add list l2 at index 1
l1.addAll(1, l2); 
System.out.println(l1); 

// Removes element from index 1 
l1.remove(1);      
System.out.println(l1); // [1, 2, 3, 2] 

// Prints element at index 3 
System.out.println(l1.get(3)); 

// Replace 0th element with 5 
l1.set(0, 5);    
System.out.println(l1);

Source:

results matching ""

    No results matching ""