Posts

Small Generics Examples

List<Number> nums = new ArrayList<Number>(); //ok List<? super Number> sink = nums; //ok //assignment is allowed. you can add element in sink list. List<? extends Number> source = nums; // ok //assignment is allowed. But you cannot add element in source list. List<List<?>> lists = new ArrayList<List<?>>(); // ok List<?> lists = new ArrayList<?>(); // COMPILE-TIME-ERROR // You could not add element in the created list Map<String, ? extends Number> map = new HashMap<String, ? extends Number>();  // compile-time error // You could not add element in the created map public void <T> check(List<? extends T> list){ list.add("1");// COMPILE-TIME-ERROR // you cannot add element in list as it uses extends } public class Maths {     public static <T> T findMax(T x, T y) {         return x > y ? x : y; // COMPILE-TIME ERROR // ident...

Generic Method

Those methods which introduce their own type parameters are called generic methods.  It is equivalent to declare a generic type, but here in method case the type parameter's scope is limited to the method only, where the type is declared.  You can also declared static generic method. Also generic constructors.  Static and non-static generic methods are allowed, as well as generic class constructors.  In generic method syntax you need to declare the generic type before the method return type. Method with type parameter: public <T> void check(T t){} Method with bounded type parameter: public <U extends Number> void check(U u){} Also you can define multiple bouded type parameters: public <T extends Insect & Birds & Animals> void checkAnimal(T t){} you can provide restrictions using the bounded type parameter.

Type Parameters

Type parameter naming conventions is single upper case letters. Type parameter are specified between <> angle brackets. i.e <T> This pair of angle brackets <>, is called the diamond. Type parameters can be provided at the class level or metod level. Type parameters provide you a way to use the same code for different types inputs. The passed data type is checked at compile time. Which checks the problems at compile time. Type parameters eliminate explicit type casting. Type parameter and Type argument both are different Test<T> here T is type parameter Test<String> here String is type argument. There can be multiple type parameters :  class Test<K,V>{} Frequently used type parameter names letters are: T - Type V - Value K - Key E - Element (It is majorly used by Java Collections Framework) N - Number Class level type parameter class Test<T>{ public void print(T t){}; public void printList(List<? extends T>...

Covariant Explained

Arrays are Covariant because an Integer is Number and array of Integer is also cosidered as Array of Number. But generics with simple type parameter are not covariant because List<Integer> is not List<Number>  because here polymorphism is apply to base type List only. Polymorphism is not applied at type parameter  <Integer> and <Number>. But you can make the generics covariant using wildcards ? super T and ? extends T . You can declare this covariant type saftey at class level or method level as per your requirements. Examples public interface Circle<T> {     public T get();     public void put(T element); public void put(Circle<T> circle); } Circle<Integer> iCircle = new CircleImpl<Integer>(3); Number num = iCircle.get(); //  here it will get the integer value in the Number type num variable. It will not give error because polymorphism is straight forward here. because You can put...

Get and Put principle

Get when you want to restrict to add new entry into data structure then you should use extends with wildcard. Means when you only get values from the data structure then you should use extends wildcard. Put When you want to put values in data structure then you should use super with wildcard. Means you need to modify the data structure then you should go use the super with wildcard. Look at the prototype of below method for understanding it better way. public static <T> void copy(List<? super T> dest, List<? extends T> src){ for (int i=0; i<srcSize; i++){          dest.set(i, src.get(i)); } } Here we are taking values from src list and adding them in dest list. If you will try to add in src list it will give you compile time error. I have already explained why it will give error in this topic:   Wildcards

Wildcards with super

Wildcards with super class MyCollection{ public static <T> void myCopy(List<? super T> dest, List<? extends T> src){ for(int i=0; i<dest.size(); i++){ dest.set(i, src.get(i)); } } } Here the phrase <? super T> means the dest list can contains any elements which are super class of type T. The phrase <? extends T> means the src list will receive any elements list which are subclasses of type T. Here the type parameter will be infered or it can be given explicitly. List<Object> objs = Arrays.<Object>asList("1","One","Birds"); List<Integer> ints = Arrays.addList(9,10,11); In below two method call type parameter is infered. MyCollections.myCopy(objs, ints); MyCollections.myCopy(objs, ints); In below three method calls we are explicitly providing type parameter. Type parameter is Object. MyCollections.<Object>myCopy(objs, ints);  Type parameter is Number. MyCollection...

Wilcards

Lets have a look at the below method definition    <T extends Human> int totalHumans(List<T> list) { } Here parameter T is only once in the method prototype, in an argument only. You can assume that if the method body does not use the type T either. In suca case you can use alternate syntax, called wildcards, It is denoted with ? symbol     int totalHumans(List<? extends Human> list) { } The two method definitions for totalHumans are similar. The meaning of <? extends Human> is: It allows any type parameter as long as it is a subclass of Human. Also when you use extends in any collection type parameter argument then you cannot manipulate  that collection. You can only get elements from that collection. Because it can lead to inappropriate data into collection if it allow to add data in that collection. Assume that collection is List<? extends Number> list, and assume you have pass the Integer list and inside met...