Posts

Showing posts from December, 2017

Defining generic methods

Generics is not limited to defining generic classes. We can define generic methods in our normal classes as well. Lets see how can we use generic methods. public static < T extends Number & Comparable> void myGenericMethod ( T obj) { System. out .println(obj.getClass().getName()) ; } As you can see in the above code snippet, we just need to define the parameter type before the method return type. Generic methods also support the bounded types as supported by the generic classes. The example for the generic method can be found  here It is even possible for constructors to be generic. Since we are talking about generic methods, lets talk a bit about method overloading. Consider the below example. We have two methods as below : void myGenericMethod(ArrayList<String> lst) {}; void myGenericMethod(ArrayList<Integer> lst) {}; Lets first take a look at how compilation happens for generic code. 1. Code compiled with generic syntax 2. Generic

Generics - Wild Card Arguments

With generics, type safety is ensured. At the same time, it can cause you to write reduntant code even in acceptable scenarios. Consider the below code : public class WildCardExample { public static void main (String[] args) { ArrayList<String> strList = new ArrayList<String>() ; strList.add( "1" ) ; strList.add( "2" ) ; strList.add( "Sandeep" ) ; ArrayList<Integer> intList = new ArrayList<Integer>() ; intList.add( 1 ) ; intList.add( 2 ) ; intList.add( 3 ) ; ArrayList<Double> doubleList= new ArrayList<Double>() ; doubleList.add( 1.1 ) ; doubleList.add( 1.2 ) ; System. out .println( "Printing string list : " ) ; printValue (strList) ; System. out .println( "Printing int list : " ) ; printValue (intList) ; System. out .println( "Printing double list : " )