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

Java Collections Framework


Core Java

History

Collection implementations in pre-JDK 1.2 versions of the Java platform included few data structure classes, but did not contain a collections framework.The standard methods for grouping Java objects were via the array, the Vector, and the Hashtable classes, which unfortunately were not easy to extend, and did not implement a standard member interface.To address the need for reusable collection data structures, several independent frameworks were developed,the most used being Doug Lea's Collections package,and ObjectSpace Generic Collection Library (JGL), whose main goal was consistency with the C++ Standard Template Library (STL).
The collections framework was designed and developed primarily by Joshua Bloch, and was introduced in JDK 1.2. It reused many ideas and classes from Doug Lea's Collections package, which was deprecated


There may be question like why we need collection or use of collection over Array


It's good to question like this, it's very common interview question - so here is answer
§ - Arrays are not resizable it's size dosen't grow at run time to solve this problem we use collection
§ - Array can hold group of elements of the same(homogeneous) type (either primitives or objects) data element , In collection we can hold homogeneous and heterogeneous elements
Here is an example of Array
public class HowtoIterateJavaArray {
  public static void main(String args[]) {
    // only int type
    int marks[5] = {98, 95, 91, 93, 97};
    //java array iteration using enhanced for loop
    for (int value : marks){
      System.out.println(value);
    }
  }
} 
§ - array is a simple linear structure. Many applications may require more complex data structure such as linked list, stack, hash table, sets, or trees.


Introduction to Collection framework


In Java, dynamically allocated data structures (such as ArrayList, LinkedList, Vector, Stack, HashSet, HashMap, Hashtable) are supported in a unified architecture called the Collection Framework, which mandates the common behaviors of all the classes.

A collection, as its name implied, is simply an object that holds a collection (or a group, a container) of objects. Each item in a collection is called an element. A framework, by definition, is a set of interfaces that force you to adopt some design practices. A well-designed framework can improve your productivity and provide ease of maintenance.

The collection framework provides a unified interface to store, retrieve and manipulate the elements of a collection, regardless of the underlying and actual implementation. This allows the programmers to program at the interfaces, instead of the actual implementation, It reduces programming effort while increasing performance. and also enables interoperability among unrelated APIs, reduces effort in designing and learning new APIs, and fosters/increase software reuse.

Java Collections Framework provides lots of different useful data types, such as linked lists (allows insertion anywhere inconstant time), resizeable array lists (like Vector ), red-black trees, hash-based maps (like Hashtable ) many more ...
The framework is based on more than a dozen collection interfaces. It includes implementations of these interfaces and algorithms to manipulate them.


The core interface

CoreInterface

Ten Key intefaces of collection framework


1- Collection interface
2- Iterator Interface
3- List interface
4- Set Interface
5- SortedSet interface
6- NavigableSet interface
7- Queue Interface
8- Map Interface
9- SortedMap interface
10- NavigableMap interface


Hierarchy view

Java.util package contains all the classes and interface for collection framework

collection


Collection Interface

List Interface

Map Interface

Set Interface

Queue Interface

Iterator Interface



Introduction to Generics (JDK 1.5)

JDK 1.5 introduces a new feature called generics to resolve this problem. Generics allow us to pass type information, in the form of , to the compiler, so that the compiler can perform all the necessary type-check during compilation to ensure type-safety at runtime.
For example, this statement with generics List (read as List of Strings) and ArrayList (read as ArrayList of Strings) informs the compiler that the List and ArrayList can hold only String object:
List lst = new ArrayList(); // read as List of Strings, ArrayList of Strings


Example - how we can print array of different type using a single Generic method

public class GenericMethodTest
{
   // generic method printArray                         
   public static < E > void printArray( E[] inputArray )
   {
      // Display array elements              
         for ( E element : inputArray ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    } 
}

Output - 
		Array integerArray contains:
		1 2 3 4 5 6
		
		Array doubleArray contains:
		1.1 2.2 3.3 4.4 
		
		Array characterArray contains:
		H E L L O
		_______________________________________

Generic Classes



A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.


Example - How to define a Generic Class


	public class Box {
	
	  private T t;
	
	  public void add(T t) {
	    this.t = t;
	  }
	
	  public T get() {
	    return t;
	  }
	
	  public static void main(String[] args) {
	     Box integerBox = new Box();
	     Box stringBox = new Box();
	    
	     integerBox.add(new Integer(10));
	     stringBox.add(new String("Hello World"));
	
	     System.out.printf("Integer Value :%d\n\n", integerBox.get());
	     System.out.printf("String Value :%s\n", stringBox.get());
	  }
	}
	
	Output - 
		Integer Value :10
		
		String Value :Hello World
		_______________________________________


Important Points about Java Generics



Generics are implemented using Type Erasure



In Java a class or an interface can be declared to define one or more type parameters and those type parameters should be provided at the time of object construction. For example,

	List <Long> list = new ArrayList <Long>();
	list.add(Long.valueOf(1));
	list.add(Long.valueOf(2));

In the example shown above a List is created which can only contain elements of type Long and if you try to add any other type of element to this list, it will give you compile time error


Generics does not support sub-typing



Generics does not support sub-typing which means that List is not considered to be a sub-type of List, where S is a subtype of T - example

List<Number> numbers = new ArrayList < Integer>(); // will not compile

You can't create [ Generic Arrays and Arrays of Generic classes of interfaces ]



You can't create generic arrays because arrays carry runtime type information about the type of elements . Arrays uses this information at runtime to check the type of the object it contains and will throw ArrayStoreException if the type does not match. But with Generics type information gets erased and the array store check will succeed in cases where it should fail.


T[] arr = new T[10];// this code will not compile

//You can't even create Arrays of Generic classes of interfaces
List <Integer>[] array = new List <Integer>[10]; // does not compile

Use of wildcards with extends or super to increase API flexibility



There are times that you need to work not only with T but also with sub types of T. For example


	boolean addAll(Collection <? extends E> c)


This ? extends E makes sure that you can not only add collection of type E but also of subtype of E. ? is called the wildcard and ? is said to be bounded by E. So,if we create a List of Number then we can not only add List of number but we can also add List of Integer or any other subtype of Number.


List<Number> numbers = new ArrayList<Number>();
ArrayList<Integer> integers = new ArrayList();
ArrayList<Long> longs = new ArrayList<Long>();
ArrayList<Float> floats = new ArrayList<Float>();
numbers.addAll(integers);
numbers.addAll(longs);
numbers.addAll(floats);


Use of Multiple Bounds



Multiple bounds is one of the generics features which most developer do not know. It allows a type variable or wildcard to have multiple bounds.
For example, if you to define constraint such as that the type should be a Number and it should implement Comparable.

 
public static <T extends Number & Comparable<? super T>> int compareNumbers(T t1, T t2){
	return t1.compareTo(t2);
}

It makes sure that you can only compare two numbers which implement Comparable. Multiple bounds follows the same constraints as followed by the a class i.e. T can't extend two classes ,
you have to first specify the class then the interface, and T can extend any number of interfaces.