Pages

Tuesday, April 21, 2015

Generic Programming in Java



Java first appeared in 1995, and it was designed to let the Java developers "write once, run anywhere". C++ was nearly at its peak while Java was born, so OOP and Portability have been fully supported since the very beginning. Any programming language has design principles, here I copied
the five primary goals in the creation of the Java language:
   1. Simple, Object-Oriented and Familiar
   2. Robust and Secure
   3. Architecture-neutral and portable
   4. High performance
   5. Interpreted, Threaded, and Dynamic 






Since then, Java has experienced lots of changes. One change is the Generics or Generic Programming introduced in Java 5. Now Generics has been widely in practice, and the Functional Programming in Java 8 makes it even more indispensable.

It's uncommon to see a method in Java Stream API like this:


public static <T> Collector<T,?,Long> counting();


or,

public static <T,K,D,A,M extends Map<K,D>> Collector<T,?,M>
       groupingBy(
Function<? super T,? extends K> classifier,
                 
Supplier<M> mapFactory,                                            Collector<? super T,A,D> downstream);



It's fun to write/play code. Here is some on Basics of Java Generics:
/**
   Code snippet to initialize the generic type
   There are 4 compilation errors:

     1, Cannot make a static reference to the non-static type T

     2, Cannot make a static reference to the non-static type T

     3, Cannot instantiate the type T

     4, Cannot create a generic array of T

**/

public class Generic<T> {



    // returns an object of the generic type

    public static T returnGenericType_static() {

        return new T();

    }
    // returns an object of the generic type

    public T returnGenericType() {

        return new T();

    }
    // returns an array of the generic type

    public T[] returnGenericArray() {

         return new T[2];

    }


}