Introduction to Collection Framework

Collections are group of objects stored in well defined manner. Earlier, Arrays are used to represent these group of objects. But, arrays are not re-sizable. size of the arrays are fixed.The Size of the arrays can not be changed once they are defined. This causes lots of problem while handling group of objects. To overcome this drawback of arrays, Collection framework or simply collections are introduced in java from JDK 1.2.

why collection !

Java Collection Framework provides some pre-defined interfaces and classes to handle the group of objects. we can store the objects like set, list, queue, map and perform operations like adding an object or removing an object or sorting the objects without much a lot of work.

Benefits of the Java Collections Framework

  • Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level plumbing required to make it work.
  • Increases program speed and quality: The Collections provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations.
  • Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth. If my network administration API furnishes a collection of node names and if your GUI toolkit expects a collection of column headings, our APIs will interoperate seamlessly, even though they were written independently.
  • Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers donot have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces.
  • Interfaces in Collection Framework

    Collection is root interface of Collection framework and Set, List and Queue all are sub- interfaces of Collection framework. These interfaces allow collections to be manipulated independently of the details of their representation

    See collection interfaces form a hierarchy

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
                Collection
    		 |
    	--------------------------------------
    	|	 	  |		  |       |	
    	Set		List	Queue	Deque
    	 |
    	SortedSet
    
    
       Map 
        |
      SortedMap	
    

    public interface Collection..

    The is symbol of generic Interface. When you declare a Collection instance you can and should specify the type of object contained in the collection. Specifying the type allows the compiler to verify that the type of object we put into the collection is correct, thus reducing errors at runtime.

    Collection : the root of the collection hierarchy. A collection represents a group of objects known as elements of object. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired.

    Set : a collection that cannot contain duplicate elements. If any paper compitition student get set of paper question.

    List : an ordered collection sequence of object. Lists can contain duplicate elements. List each element is inserted and can access elements by their integer index position. If you have used Vector, you are familiar with the general flavor of List.

    Queue : collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.

    Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements natural ordering. Whatever the ordering used, the head of the queue is the element that would be removed by a call to remove or poll.

    Deque : is collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Deque provides additional insertion, extraction, and inspection operations. Deques can be used both as FIFO (first-in, first-out) and LIFO (last-in, first-out).

    Map : is an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.

    SortedSet : is Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.

    SortedMap : is Map that maintains its mappings in ascending key order. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories.

    Collection Interface

    The Collection is a group of objects called as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired

     List list = new ArrayList(c);
     

    In above , c can be List, Set or another kind of Collection.

    The Collection interface methods

  • int size()
  • boolean isEmpty()
  • boolean contains(Object element)
  • boolean add(E element)
  • boolean remove(Object element)
  • Iterator iterator()
  • There are three ways to traverse collections

  • using aggregate operations
  • with the for-each construct
  • by using Iterators
  • Aggregate Operations using jdk 1.8

     myShapesCollection.stream()
    .filter(e -> e.getColor() == Color.RED)
    .forEach(e -> System.out.println(e.getName()));
    

    for-each Construct

    	for (Object o : collection)
    		System.out.println(o);
    

    Iterators : An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator method

     public interface Iterator {
        boolean hasNext();
        E next();
        void remove(); //optional
    }
     

    Collection Interface Bulk Operations

  • containsAll : returns true if the target Collection contains all of the elements in the specified Collection.
  • addAll : adds all of the elements in the specified Collection to the target Collection.
  • removeAll : removes from the target Collection all of its elements that are also contained in the specified Collection
  • retainAll : removes from the target Collection all its elements that are not also contained in the specified Collection. That is, it retains only those elements in the target Collection that are also contained in the specified Collection
  • clear : removes all elements from the Collection.
  • Collection Interface Array Operations

    The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input.

    Object[] a = c.toArray();
    String[] a = c.toArray(new String[0]);
    
    

    Set in Collection

    Collection Set is a Collection that cannot contain duplicate elements. The Set interface inherite only methods from Collection and set the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.

    There are three types of Set Interface

  • HashSet
  • TreeSet
  • LinkedHashSet

  • HashSet

    HashSet class implements the Set interface. It makes no guarantees as to the iteration order of the set. mean ,it does not guarantee that the order will remain constant over time. This class permits the null element.

    HashSet class offers constant time performance for the basic operations (add, contains, remove and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance is size (the number of elements) plus the capacity of the backing HashMap instance (the number of buckets). So, it is very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

    HashSet implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be wrapped using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set

     Set s = Collections.synchronizedSet(new HashSet(...));

    The iterators returned by this class is iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator is own remove method, the Iterator throws a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

    Method of HashSet

  • public boolean add(E e) : Adds the specified element to this set if it is not already present.
  • public boolean remove(Object o) : Removes the specified element from this set if it is present.
  • public void clear() : Removes all of the elements from this set. The set will be empty after this call returns.
  • public Object clone() :Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
  • public Spliterator spliterator() : Creates a late-binding and fail-fast Spliterator over the elements in this set.

  • ------------------------------------------------------

    TreeSet

    A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

    Note that this implementation is not synchronized. If multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be wrapped using the Collections.synchronizedSortedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

     SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

    The iterators returned by this class is iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator is own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

    Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis.

    Method of TreeSet

  • public Iterator iterator() : Returns an iterator over the elements in this set in ascending order.
  • public Iterator descendingIterator() : eturns an iterator over the elements in this set in descending order.
  • public NavigableSet descendingSet() : Returns a reverse order view of the elements contained in this set. The descending set is backed by this set, so changes to the set are reflected in the descending set, and vice-versa. If either set is modified while an iteration over either set is in progress (except through the iterator is own remove operation), the results of the iteration are undefined.
  • public int size() : Returns the number of elements in this set (its cardinality).
  • public boolean isEmpty() : Returns true if this set contains no elements.
  • public boolean contains(Object o) : Returns true if this set contains the specified element.
  • public boolean add(E e) : Adds the specified element to this set if it is not already present
  • public boolean remove(Object o) : Removes the specified element from this set if it is present
  • public void clear() : Removes all of the elements from this set. The set will be empty after this call returns.
  • public boolean addAll(Collection c) : Adds all of the elements in the specified collection to this set.
  • public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) : Returns a view of the portion of this set whose elements range from fromElement to toElement. If fromElement and toElement are equal, the returned set is empty unless fromInclusive and toInclusive are both true. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.
  • public SortedSet subSet(E fromElement, E toElement) : Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive
  • public SortedSet headSet(E toElement) : Returns a view of the portion of this set whose elements are strictly less than toElement. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports
  • public SortedSet tailSet(E fromElement) : Returns a view of the portion of this set whose elements are greater than or equal to fromElement
  • public Comparator comparator() : Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
  • public E first() : Returns the first (lowest) element currently in this set.
  • public E last() : Returns the last (highest) element currently in this set.
  • public E lower(E e) : Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
  • public E floor(E e) : Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
  • public Object clone() : Returns a shallow copy of this TreeSet instance. (The elements themselves are not cloned.

  • ------------------------------------------------------

    LinkedHashSet

    public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable

    Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

         void foo(Set s) {
             Set copy = new LinkedHashSet(s);
             ...
         }
     

    Note that this implementation is not synchronized. If multiple threads access a linked hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be wrapped using the Collections.synchronizedSet method.

    Set s = Collections.synchronizedSet(new LinkedHashSet(...));

    Method of LinkedHashSet

    public Spliterator spliterator() : Creates a late-binding and fail-fast Spliterator over the elements in this set.

    Set Interface Basic Operations

    import java.util.*;
    import java.util.stream.*;
    
    public class findWorkd {
        public static void main(String[] args) {
            Set distinctWords = Arrays.asList(args).stream()
    		.collect(Collectors.toSet()); 
            System.out.println(distinctWords.size()+ 
                               " distinct words: " + 
                               distinctWords);
        }
    }
    

    Using the for-each Construct:

    import java.util.*;
    
    public class findWorkd {
        public static void main(String[] args) {
            Set s = new HashSet();
            for (String a : args)
                   s.add(a);
                   System.out.println(s.size() + " distinct words: " + s);
        }
    }
    

    b>Set Interface Bulk Operations

  • s1.containsAll(s2) ? returns true if s2 is a subset of s1. (s2 is a subset of s1 if set s1 contains all of the elements in s2.)
  • s1.addAll(s2) ? transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all of the elements contained in either set.)
  • s1.retainAll(s2) ? transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.)
  • s1.removeAll(s2) ? transforms s1 into the (asymmetric) set difference of s1 and s2. (For example, the set difference of s1 minus s2 is the set containing all of the elements found in s1 but not in s2.)
  • import java.util.*;
    
    public class findWorkd {
        public static void main(String[] args) {
            Set uniques = new HashSet();
            Set dups    = new HashSet();
    
            for (String a : args)
                if (!uniques.add(a))
                    dups.add(a);
    
            // Destructive set-difference
            uniques.removeAll(dups);
    
            System.out.println("Unique words:    " + uniques);
            System.out.println("Duplicate words: " + dups);
        }
    }
    

    List in Collection

    The Collection list is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.

    List interface have operations :

  • Positional access : manipulates elements based on their numerical position in the list. This includes methods such as get, set, add, addAll, and remove.
  • Search : searches for a specified object in the list and returns its numerical position. Search methods include indexOf and lastIndexOf.
  • Iteration : extends Iterator semantics to take advantage of the list is sequential nature. The listIterator methods provide this behavior.
  • Range-view : The sublist method performs arbitrary range operations on the list.
  • List of method

  • int size(): Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
  • boolean isEmpty() : Returns true if this list contains no elements.
  • boolean contains(Object o) : Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
  • Iterator iterator(): Returns an iterator over the elements in this list in proper sequence.
  • Object[] toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).
  • T[] toArray(T[] a) : Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.
  • boolean add(E e) : Appends the specified element to the end of this list (optional operation).
  • boolean remove(Object o)
  • boolean containsAll(Collection c): Returns true if this list contains all of the elements of the specified collection.
  • boolean addAll(Collection c)
  • boolean removeAll(Collection c): Removes from this list all of its elements that are contained in the specified collection (optional operation).
  • boolean retainAll(Collection c): Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.
  • default void sort(Comparator c): Sorts this list according to the order induced by the specified Comparator.
  • void clear(): Removes all of the elements from this list (optional operation). The list will be empty after this call returns.
  • boolean equals(Object o): Compares the specified object with this list for equality.
  • int hashCode(): Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation
  •      int hashCode = 1;
         for (E e : list)
             hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
    
  • E get(int index): Returns the element at the specified position in this list.
  • E set(int index, E element) : Replaces the element at the specified position in this list with the specified element (optional operation).
  • void add(int index, E element): Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
  • E remove(int index): Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
  • int indexOf(Object o): Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
  • int lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
  • The Java collection platform contains two general-purpose List implementations. ArrayList, which is usually the better-performing implementation, and LinkedList which offers better performance under certain circumstances.

    Positional Access and Search Operations

    The basic positional access operations are get, set, add and remove.

    The addAll operation inserts all the elements of the specified Collection starting at the specified position. The elements are inserted in the order they are returned by the specified Collection is iterator.

    Example of swap two indexed values in a List.

    public static  void swap(List a, int i, int j) {
        E tmp = a.get(i);
        a.set(i, a.get(j));
        a.set(j, tmp);
    }
    

    Iterators

    An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved.

    Method of Iterator

  • boolean hasNext(): Returns true if the iteration has more elements.
  • E next(): Returns the next element in the iteration.
  • default void remove() : Removes from the underlying collection the last element returned by this iterator.
  • Example of Iterator

    public class IterationExample {
    
        public static void main(String[] args) {
            List list = Arrays.asList(1, 2, 3,4);
            list.stream().forEach(elem -> System.out.println("element " + elem));
        }
    }
    

    ListIterator

    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.

    The three methods that ListIterator inherits from Iterator (hasNext, next, and remove) do exactly the same thing in both interfaces. The hasPrevious and the previous operations are exact analogues of hasNext and next. The former operations refer to the element before the (implicit) cursor, whereas the latter refer to the element after the cursor. The previous operation moves the cursor backward, whereas next moves it forward.

    import java.util.*;
    
    public class ListIteratorExample {
          public static void main(String[] args) {
    
                List li = new ArrayList();
                li = Arrays.asList(1, 6, 4, 7);
                //List li2 = new ArrayList();
                int z = li.size();
                List li2 = new ArrayList();
    
                /**
                for (int index = 0; index < ints.length; index++)
                {
                    li.add(ints[index]);
                }
                 ListIterator it = li.listIterator(z);       
            while(it.hasPrevious()){
                //System.out.print(it.previous() + " ");
                int k = it.previous();
                System.out.print(k + " ");
                li2.add(k);
            }
    
            /**
                Now that I have filled li2, I create my ListIterator it2.
            **/
            ListIterator it2 = li2.listIterator();  
            while(it2.hasNext()){
                int p = it2.next();
                System.out.print(p + " ");
            }       
         }
    }
    

    List Algorithms

  • sort ? sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.)
  • shuffle ? randomly permutes the elements in a List.
  • reverse ? reverses the order of the elements in a List.
  • rotate ? rotates all the elements in a List by a specified distance.
  • swap ? swaps the elements at specified positions in a List.
  • replaceAll ? replaces all occurrences of one specified value with another.
  • fill ? overwrites every element in a List with the specified value.
  • copy ? copies the source List into the destination List.
  • binarySearch ? searches for an element in an ordered List using the binary search algorithm.
  • indexOfSubList ? returns the index of the first sublist of one List that is equal to another.
  • lastIndexOfSubList ? returns the index of the last sublist of one List that is equal to another.
  • ArrayList

    ArrayList is resizable-array implementation of the List interface.It Implements all optional list operations, and permits all elements, including null.

    In ArrayList, the size, isEmpty, get, set, iterator, and listIterator operations run in constant time. In ArrayList, 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 (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

    Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

    An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

    Method details of ArrayList

  • ublic void trimToSize(): Trims the capacity of this ArrayList instance to be the list is current size. An application can use this operation to minimize the storage of an ArrayList instance.
  • public void ensureCapacity(int minCapacity): Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
  • public int size() : Returns the number of elements in this list.
  • public boolean isEmpty() : Returns true if this list contains no elements.public boolean contains(Object o) : Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
  • public int indexOf(Object o): Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
  • public int lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
  • public Object clone(): Returns a shallow copy of this ArrayList instance. (The elements themselves are not copied.)
  • public Object[] toArray(): Returns an array containing all of the elements in this list in proper sequence (from first to last element).
  • public T[] toArray(T[] a) : Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.
  • public E get(int index) : Returns the element at the specified position in this list.
  • public E set(int index, E element) :Replaces the element at the specified position in this list with the specified element.
  • public boolean add(E e): Appends the specified element to the end of this list.
  • public E remove(int index): Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
  • public boolean remove(Object o) : Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).
  • public void clear(): Removes all of the elements from this list. The list will be empty after this call returns.
  • public boolean addAll(Collection c): Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection is Iterator.
  • public boolean addAll(int index, Collection c): Inserts all of the elements in the specified collection into this list, starting at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices).
  • public ListIterator listIterator(int index) : Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to previous would return the element with the specified index minus one.
  • public ListIterator listIterator(): Returns a list iterator over the elements in this list (in proper sequence).
  • public Iterator iterator(): Returns an iterator over the elements in this list in proper sequence.
  • public void sort(Comparator c): Sorts this list according to the order induced by the specified Comparator. All elements in this list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
  • 	import java.util.*;  
    	class TestArrayList{  
    	 public static void main(String args[]){  
    	  ArrayList list=new ArrayList();
    	  list.add("Ravi");//Adding object in arraylist  
    	  list.add("raju");  
    	  list.add("Ravi");  
    	  list.add("ramu");  
    	  list.add("Pari");  
    	  //Traversing list through Iterator  
    	  Iterator itr=list.iterator();  
    	  while(itr.hasNext()){  
    	   System.out.println(itr.next());  
    	  }  
    	 }  
    	}  
    

    output

    Ravi
    raju
    Ravi
    ramu
    Pari
    

    LinkedList

  • Doubly-linked list implementation of the List and Deque interfaces
  • Maintains insertion order
  • LinkedList list not syncsynchronized
  • Doubly-linked figure

    null-----node value 10-----node value 20-----node value 30-----null

    Method of Doubly-linked

  • void add(int index, Object element) : It is used to insert the specified element at the specified position index in a list.
  • void addFirst(Object o) : It is used to insert the given element at the beginning of a list.
  • public E getFirst() : Returns the first element in this list.
  • public E getLast() : Returns the last element in this list.
  • public E removeFirst() : Removes and returns the first element from this list.
  • public E removeLast() :Removes and returns the last element from this list.
  • public boolean remove(Object o): Removes the first occurrence of the specified element from this list, if it is present
  • public boolean addAll(Collection c): Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection is iterator.
  • public void clear(): Removes all of the elements from this list. The list will be empty after this call returns.
  • public E get(int index): Returns the element at the specified position in this list.
  • Link
    Eng. Ravi Kumar Verma

    Simple and dept learning technology is very important part in software development. Same story has been implemented at this site, so learn and implement the inovative things, Thanks

    Ravi Kumar Verma