www.000webhost.com
/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ List interface


List Interface


Core Java

A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for the following:


Positional access — manipulates elements based on their numerical position in the list - The basic positional access operations (get, set, add and remove)


Search — searches for a specified object in the list and returns its numerical position - The search operations indexOf and lastIndexOf


Iteration — extends Iterator semantics to take advantage of the list's sequential nature - the Iterator returned by List's iterator operation returns the elements of the list in proper sequence


Range-view — performs arbitrary range operations on the list - subList(int fromIndex, int toIndex), returns a List view


Elements can be inserted or accessed by their position in the list, using a zero-based index.
Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.

Being a Collection subtype all methods in the Collection interface are also available in the List interface. In addition List defines some of its own, which are summarized below.



void add(int index, Object obj)
			//Inserts obj into the invoking list at the index passed in index. 
			//Any preexisting elements at or beyond the point of insertion are shifted up. 
			//Thus, no elements are overwritten.

boolean addAll(int index, Collection c)
			//Inserts all elements of c into the invoking list at the index passed in index. 
			//Any preexisting elements at or beyond the point of insertion are shifted up. 
			//Thus, no elements are overwritten. Returns true if the invoking list 
			//changes and returns false otherwise.
	
Object get(int index)
			//Returns the object stored at the specified index within the invoking collection.

int indexOf(Object obj)
			//Returns the index of the first instance of obj in the invoking list. 
			//If obj is not an element of the list, .1 is returned.

int lastIndexOf(Object obj)
			//Returns the index of the last instance of obj in the invoking list. 
			//If obj is not an element of the list, .1 is returned.
	
ListIterator listIterator( )
			//Returns an iterator to the start of the invoking list.

ListIterator listIterator(int index)
			Returns an iterator to the invoking list that begins at the specified index.

Object remove(int index)
			//Removes the element at position index from the invoking list and returns
			//the deleted element. The resulting list is compacted. 
			//That is, the indexes of subsequent elements are decremented by one
		
Object set(int index, Object obj)
			//Assigns obj to the location specified by index within the invoking list.

List subList(int start, int end)
			//Returns a list that includes elements from start to end.1 in the invoking list.
			//Elements in the returned list are also referenced by the invoking object.

Here is an example how to use List, with few of it's method

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class ListExample {

    public static void main(String[] args) {

        // List Example implement with ArrayList
        List ls=new ArrayList();

        ls.add("one");
        ls.add("Three");
        ls.add("two");
        ls.add("four");

        Iterator it=ls.iterator();

//how to iterate List 
        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value : "+value);
        }
    }
}

Output
List Value : one
List Value : Three
List Value : two
List Value : four

Since List is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following List implementations in the Java Collections API:


java.util.ArrayList

java.util.LinkedList

java.util.Vector

java.util.Stack


java.util.ArrayList


Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time


ArrayList Class Constructors


	ArrayList()
		//This constructor is used to create an empty list with an initial capacity sufficient to hold 10 elements.

	ArrayList(Collection‹? extends E › c)
		//This constructor is used to create a list containing the elements of the specified collection.
	
	ArrayList(int initialCapacity)
		//This constructor is used to create an empty list with an initial capacity
		

Example of ArrayList with Source code


java.util.ArrayList.get() method

package com.javaessential;

import java.util.ArrayList;

public class ArrayListgetMethodDemo {
   public static void main(String[] args) {
      
    // create an empty array list with an initial capacity
    //we can also do like - ArrayList arrlist = new ArrayList(); try your own 
    ArrayList arrlist = new ArrayList(5);

    // adding elements in arrayList using add() method
    arrlist.add(15);
    arrlist.add(22);
    arrlist.add(30);
    arrlist.add(40);

    // let us print all the elements available in list
    for (Integer number : arrlist) {
      System.out.println("Number = " + number + ";");
    } 
	
    // retrieves element at 4th postion
    int retval=arrlist.get(3);
	System.out.println("Retrieved element is = " + retval + ";");	   
  }
} 

Output 
	Number = 15;
	Number = 22;
	Number = 30;
	Number = 40;
	Retrieved element is = 40;

ArrayList remove() method example

import java.util.*;

public class ArrayListRemoveDemo {
   public static void main(String args[]) {
      // create an array list
      ArrayList al = new ArrayList();
      System.out.println("Initial size of al: " + 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");
      al.add(1, "A2");
      System.out.println("Size of al after additions: " + al.size());

      // display the array list
      System.out.println("Contents of al: " + al);
      // Remove elements from the array list
      al.remove("F");
      al.remove(2);
      System.out.println("Size of al after deletions: " + al.size());
      System.out.println("Contents of al: " + al);
   }
}

output
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

convert an ArrayList into array using java.util.Arraylist.toArray() method

package com.javaessential;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      
    // create an empty array list with an initial capacity
    ArrayList arrlist = new ArrayList();

    // use add() method to add values in the list
    arrlist.add(10);
    arrlist.add(12);
    arrlist.add(31);
    arrlist.add(49);
	
    System.out.println("Printing elements of array1");

    // let us print all the elements available in list
    for (Integer number : arrlist) {
      System.out.println("Number = " + number);
    }  

    // toArray copies content into other array
    Integer list2[] = new Integer[arrlist.size()];
    list2 = arrlist.toArray(list2);

    System.out.println("Printing elements of array2");

    // let us print all the elements available in list
    for (Integer number : list2) {
      System.out.println("Number = " + number);
    }
  }
} 

Output
Printing elements of array1
Number = 10
Number = 12
Number = 31
Number = 49
Printing elements of array2
Number = 10
Number = 12
Number = 31
Number = 49

java.util.LinkedList

public class LinkedList
extends AbstractSequentialList
implements List, Deque, Cloneable, Serializable

The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list data structure. The LinkedList class supports two constructors. The first constructor builds an empty linked list:

	LinkedList( )
		//The following constructor builds a linked list that is initialized with the elements of the collection c.

	LinkedList(Collection c)
		//Apart from the methods inherited from its parent classes, LinkedList defines following methods:

If you want to insert the data in the linkedList then use add() method. The hasNext() method returns true if the iterator contains more elements and the next() method returns the next element in the iteration. To insert and remove the data at first, last and specified position in the linkedList, you use the addFirst(), addLast(), add(), removeFirst(), removeLast() and remove() methods. To retrieve the element with respect to a specified position use the getFirst(), getLast() and get() methods.


Below programs illustrates several of the methods supported by LinkedList:


LinkedList example with source code

import java.util.*;

public class LinkedListDemo {

   public static void main(String args[]) {
      // create a linked list
      LinkedList ll = new LinkedList();
      // add elements to the linked list
      ll.add("F");
      ll.add("B");
      ll.add("D");
      ll.add("E");
      ll.add("C");
      ll.addLast("Z");
      ll.addFirst("A");
      ll.add(1, "A2");
      System.out.println("Original contents of ll: " + ll);

      // remove elements from the linked list
      ll.remove("F");
      ll.remove(2);
      System.out.println("Contents of ll after deletion: "
       + ll);
      
      // remove first and last elements
      ll.removeFirst();
      ll.removeLast();
      System.out.println("ll after deleting first and last: "
       + ll);

      // get and set a value
      Object val = ll.get(2);
      ll.set(2, (String) val + " Changed");
      System.out.println("ll after change: " + ll);
   }
}

output - 
		Original contents of ll: [A, A2, F, B, D, E, C, Z]
		Contents of ll after deletion: [A, A2, D, E, C, Z]
		ll after deleting first and last: [A2, D, E, C]
		ll after change: [A2, D, E Changed, C]


complete LinkedList example with source code

 import java.util.*;

public class LinkedListCompleteExample{
  public static void main(String[] args) {
  System.out.println("Linked List Example!");
  LinkedList list = new LinkedList();
  int num1 = 11, num2 = 22, num3 = 33, num4 = 44;
  int size;
  Iterator iterator;
  //Adding data in the list
  list.add(num1);
  list.add(num2);
  list.add(num3);
  list.add(num4);
  size = list.size();
  System.out.print( "Linked list data: ");  
  //Create a iterator
  iterator = list.iterator(); 
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  //Check list empty or not
  if (list.isEmpty()){
  System.out.println("Linked list is empty");
  }
  else{
  System.out.println( "Linked list size: " + size);
  }
  System.out.println("Adding data at 1st location: 55");
  //Adding first
  list.addFirst(55);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  System.out.println("Adding data at last location: 66");
  //Adding last or append
  list.addLast(66);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  System.out.println("Adding data at 3rd location: 55");
  //Adding data at 3rd position
  list.add(2,99);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Retrieve first data
  System.out.println("First data: " + list.getFirst());
  //Retrieve lst data
  System.out.println("Last data: " + list.getLast());
  //Retrieve specific data
  System.out.println("Data at 4th position: " + list.get(3));
  //Remove first
  int first = list.removeFirst();
  System.out.println("Data removed from 1st location: " + first);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove last
  int last = list.removeLast();
  System.out.println("Data removed from last location: " + last);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove 2nd data
  int second = list.remove(1);
  System.out.println("Data removed from 2nd location: " + second);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove all
  list.clear();
  if (list.isEmpty()){
  System.out.println("Linked list is empty");
  }
  else{
  System.out.println( "Linked list size: " + size);
  }
  }
}

output - 

Linked List Example!
Linked list data: 11 22 33 44
Linked list size: 4
Adding data at 1st location: 55
Now the list contain: 55 11 22 33 44
Now the size of list: 5
Adding data at last location: 66
Now the list contain: 55 11 22 33 44 66
Now the size of list: 6
Adding data at 3rd location: 55
Now the list contain: 55 11 99 22 33 44 66
Now the size of list: 7
First data: 55
Last data: 66
Data at 4th position: 22
Data removed from 1st location: 55
Now the list contain: 11 99 22 33 44 66
Now the size of list: 6
Data removed from last location: 66
Now the list contain: 11 99 22 33 44
Now the size of list: 5
Data removed from 2nd location: 99
Now the list contain: 11 22 33 44
Now the size of list: 4
Linked list is empty


java.util.Vector


Vector class (a growable array).


Vector implements a dynamic array. It is similar to ArrayList, but with two differences:

Vector is synchronized.

Vector contains many legacy methods that are not part of the collections framework.

Vector proves to be very useful if you don't know the size of the array in advance, or you just need one that can change sizes over the lifetime of a program.


Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as elements are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. Setting the capacity to what you want before inserting a large number of objects will reduce the amount of incremental reallocation. You can safely ignore the capacity and the vector will still work correctly.


The Vector class supports four constructors. The first form creates a default vector, which has an initial size of 10:

	Vector( )
			//The second form creates a vector whose initial capacity is specified by size:

	Vector(int size)
			//The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward:

	Vector(int size, int incr)
			//The fourth form creates a vector that contains the elements of collection c:

	Vector(Collection c)
			//Apart from the methods inherited from its parent classes, Vector defines following methods:

Example of Vector with Source code


example of few methods from Vector

import java.util.*;

public class VectorDemo {

   public static void main(String args[]) {
      // initial size is 3, increment is 2
      Vector v = new Vector(3, 2);
      System.out.println("Initial size: " + v.size());
      System.out.println("Initial capacity: " +
      v.capacity());
      v.addElement(new Integer(1));
      v.addElement(new Integer(2));
      v.addElement(new Integer(3));
      v.addElement(new Integer(4));
      System.out.println("Capacity after four additions: " +
          v.capacity());

      v.addElement(new Double(5.45));
      System.out.println("Current capacity: " +
      v.capacity());
      v.addElement(new Double(6.08));
      v.addElement(new Integer(7));
      System.out.println("Current capacity: " +
      v.capacity());
      v.addElement(new Float(9.4));
      v.addElement(new Integer(10));
      System.out.println("Current capacity: " +
      v.capacity());
      v.addElement(new Integer(11));
      v.addElement(new Integer(12));
      System.out.println("First element: " +
         (Integer)v.firstElement());
      System.out.println("Last element: " +
         (Integer)v.lastElement());
      if(v.contains(new Integer(3)))
         System.out.println("Vector contains 3.");
      // enumerate the elements in the vector.
      Enumeration vEnum = v.elements();
      System.out.println("\nElements in vector:");
      while(vEnum.hasMoreElements())
         System.out.print(vEnum.nextElement() + " ");
      System.out.println();
   }
}

output - 
		Initial size: 0
		Initial capacity: 3
		Capacity after four additions: 5
		Current capacity: 5
		Current capacity: 7
		Current capacity: 9
		First element: 1
		Last element: 12
		Vector contains 3.
		
		Elements in vector:
		1 2 3 4 5.45 6.08 7 9.4 10 11 12



java.util.Stack


Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

	boolean empty()
			//Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.

	Object peek( )
			//Returns the element on the top of the stack, but does not remove it.

	Object pop( )
			//Returns the element on the top of the stack, removing it in the process.

	Object push(Object element)
			//Pushes element onto the stack. element is also returned.

	int search(Object element)
			//Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, .1 is returned.

How to use Stack in java - Examples


Example of Stack with source code

import java.util.*;

public class StackDemo {

   static void showpush(Stack st, int a) {
      st.push(new Integer(a));
      System.out.println("push(" + a + ")");
      System.out.println("stack: " + st);
   }

   static void showpop(Stack st) {
      System.out.print("pop - ");
      Integer a = (Integer) st.pop();
      System.out.println(a);
      System.out.println("stack: " + st);
   }

   public static void main(String args[]) {
      Stack st = new Stack();
      System.out.println("stack: " + st);
      showpush(st, 42);
      showpush(st, 66);
      showpush(st, 99);
      showpop(st);
      showpop(st);
      showpop(st);
      try {
         showpop(st);
      } catch (EmptyStackException e) {
         System.out.println("empty stack");
      }
   }
}

output - 
		stack: [ ]
		push(42)
		stack: [42]
		push(66)
		stack: [42, 66]
		push(99)
		stack: [42, 66, 99]
		pop - 99
		stack: [42, 66]
		pop - 66
		stack: [42]
		pop - 42
		stack: [ ]
		pop - empty stack

Stack Example with user Input - complete source code


import java.util.*;

class Operations{
      Scanner sc=new Scanner(System.in);

      int Maxsize,i,p,c=-1;
      int stk[];
      Operations(int m)
      {
            Maxsize=m;
            stk=new int[Maxsize];
      }
      void push()
      {
            if(c==(Maxsize-1))
                  System.out.println("\tStack Overflow");
            else
            {
                  System.out.println("Input an element : ");
                  i=sc.nextInt();
                  c++;  stk[c]=i;
            }
      }
      void pop()
      {
            if(c==-1)
                  System.out.println("\tStack is empty");
            else
            {
                  p=stk[c]; c--;
                  System.out.println("\t Element Poped : "+p);
            }
      }
      void display()
      {
            if(c==-1)
                  System.out.println("Stack is empty");
            else
            {
                  System.out.println("\nStack Status : ");
                  for(i=c;i>=0;i--)
                        System.out.println("\t "+stk[i]);
            }
      }
} 

class Stack{

      public static void main(String a[]){

            Scanner sc=new Scanner(System.in);

            int choice,size,i;

            System.out.println("Enter the size of stack : ");

            size=sc.nextInt(); 

            Operations s=new Operations(size); 
            for(;;)
            {
                  System.out.println("Enter your choice : ");

                  System.out.println(" 1. Push \n 2. Pop \n 3. Display Stack \n 4. exit  \t :::: ");

                  choice=sc.nextInt();

                  switch(choice)
                  {
                        case 1: s.push();
                                    break;

                        case 2: s.pop();
                                    break;

                        case 3: s.display();
                                    break;

                        default: System.exit(0);
                  }
            }
      }
}

output - 
Enter the size of stack :

4

Enter your choice :

1. Push
2. Pop
3. Display Stack
4. exit    ::::
1
Input an element :
1
Enter your choice :
1. Push
2. Pop
3. Display Stack
4. exit    ::::
1
Input an element :
19
Enter your choice :
1. Push
2. Pop
3. Display Stack
4. exit    ::::
3 
Stack Status :
       19
       1
Enter your choice :
1. Push
2. Pop
3. Display Stack
4. exit    ::::
2
       Element Poped : 19
Enter your choice :
1. Push
2. Pop
3. Display Stack
4. exit    ::::
2
       Element Poped : 1
Enter your choice :
1. Push
2. Pop
3. Display Stack
4. exit    ::::
2
      Stack is empty
Enter your choice :
1. Push
2. Pop
3. Display Stack
4. exit    ::::
3
      Stack is empty
Enter your choice :
1. Push
2. Pop
3. Display Stack
4. exit    ::::
 

Click here to continue reading - Set Interface