List Implementations


List is an ordered collection also known as sequence.

The user can access elements by their integer index .list allows duplicates
it allows null reference(we can store null values in list)
we can store elements and objects also. Ex:student's list,employ numbers

List Implementations

  • ArrayList
  • Vector
  • LinkedList


ArrayList:

  This list is most frequently used list  

Resizable array implementation of the list interface ArrayList supports both Iterator and ListIterator for traversing elements. 

ArrayList is not synchronized and should not be shared between multiple threads.
If multiple threads access a Java ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (As per Java doc a structural .

using  Collections.synchronizedList method we can change to synchronized list.


Example using ArrayList:

package com.collections;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
 *
 * @author surendra
 * basic example of arraylist.
 */
public class ArrayListExample {
public static void main(String[] args) {
//Creating arraylist generics type it stores only string values
ArrayList<String> cityNames=new ArrayList<String>();
//Adding elements to arraylits using add method
cityNames.add("hyderbad");
cityNames.add("chennai");
cityNames.add("delhi");
cityNames.add("bangalore");
cityNames.add("kolkata");
System.out.println(cityNames);//:[hyderbad, chennai, delhi, bangalore, kolkata]
System.out.println("size is::"+cityNames.size());//size is::5
//Getting elements based on index
System.out.println(cityNames.get(1)+":::index one element");//chennai:::index one element
//Finding index position based on iteam suing indexOf method.
System.out.println(cityNames.indexOf("delhi")+"::delhi postion in list");//2::delhi postion in list
//Retrieving Item from arrayList in a foreach loop
for(String cityName:cityNames){
System.out.println("city name :::"+cityName);  /* city name :::hyderbad
                                                              city name :::chennai
                                                              city name :::delhi
                                                              city name :::bangalore
                                                              city  name :::kolkat*/
}
////isEmpty() will return true if List is empty
    System.out.println(cityNames.isEmpty()+"::is list empty");//false
 
 
    //Removing elements base on index
 
    cityNames.remove(0);
 
    //Removing elements base on iteam
 
    cityNames.remove("chennai");
 
    System.out.println("size after removing:::"+cityNames.size());//size after removing:::3
 
   // Replacing an element at a particular index
    cityNames.set(2, "hyderbad");
 
 
 
    //Creating Synchronized ArrayList
 
 
    Collections.synchronizedList(cityNames);
 
    //Clearing all data from ArrayList
 
    cityNames.clear();
    System.out.println(cityNames.size()+":size ");//0:size
 
 
 
}
}

Vector:
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.

LinkedList:

The LinkedList is a part of collection that constructs a list containing the elements of the specified collection. Iterator methods returns the values in the order in which they are stored.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 theaddFirst()addLast()add()removeFirst()removeLast() and remove() methods. To retrieve the element with respect to a specified position use the getFirst()getLast() and get() methods.

Example:


package com.collections;
import java.util.List;
import java.util.LinkedList;
/**
 *
 * @author surendra
 *
 */
public class LinkedListExamples {
public static void main(String[] args) {
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);
}
}

Comparison between ArrayList and Vecor and LinkedList:

In  this three mostly  used one is arraylist so i comparing array-list to both list here....
ArrayList Vs Vector:
Main difference is synchronization means threds safety when we required threds safety vector is best
option because it synchronized list.only one instance for multiple threads but arraylist is not synchronized list.
multiple instance will be created for multiple  threads  

    Array list not synchronized so performance is better than vector.

ArrayList can be synchronized using the java collections framework utility class and then ArrayList itself can be used in place of Vector.

ArrayList Vs LinkedList:ArrayList implements the RandomAccess interface, and LinkedList does not. Note that Collections.binarySearch does take advantage of the RandomAccess property, to optimize searches. A LinkedList does not support efficient random access

An ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. The get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. (see What is the advantage of using an Iterator compared to the get(index) method?)
An ArrayList is much faster than LinkedList doing a binary search on the large list of sorted element.


A LinkedList are more efficient speed wise than ArrayList when inserting and removing at random places in the list multiple times. If you're just adding to the end of the list, an ArrayList is what you want.


A LinkedList is faster than an ArrayList when elements are only added to the beginning of the list.
A LinkedList has a simple growth pattern of just adding and removing nodes when it needs to, but the ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the buffer is too small it will create a new one of size (n*3)/2+1 where n is the number of elements of the current buffer and there will be a significant amount of space wasted at the end.


The reversing a LinkedList using Collections.reverse. The internal algorithm does this, and gets reasonable performance, by using forward and backward iterators.

Mostley whenever insertion and removing elements operations are more compare to reading 

Better to choose LinkedList when ever reading operation is more beset choice is ArrayList

-----------------------------------------------------------------------------------------------------------


  • The default initial capacity of an ArrayList is pretty small (10 from Java 1.4 - 6). But since the underlying implementation is an array, the array must be resized if you add a lot of elements. To avoid the high cost of resizing when you know you're going to add a lot of elements, construct the ArrayList with a higher initial capacity.

Author

Written by Admin

Aliquam molestie ligula vitae nunc lobortis dictum varius tellus porttitor. Suspendisse vehicula diam a ligula malesuada a pellentesque turpis facilisis. Vestibulum a urna elit. Nulla bibendum dolor suscipit tortor euismod eu laoreet odio facilisis.

0 comments: