Generics helps reusability of code
Generics are one of the most useful features of Java.Generics allows re usability of code.The same generic type,such as class,can work with different data types.Before generics we defined a class which work with only
specific data type.for example if we declare a class as:
public class SampleClass{ Integer obj; //operations for integer type }
the above class works with only integer data type.If you want to implement operations for float data type then you need to implement another class for float type.So such implementations results in duplicate logic.
When we use generic class we define a single class which works with different data types.
public class SampleClass<T>{ public static void main(String []args){ System.out.println("Hello World"); SampleClass<Integer> obj1=new SampleClass<Integer>(); obj1.Set(1); System.out.println(obj1.Get()); } T obj; void Set(T a) { obj=a; } T Get() { return obj; } }
Generics avoid casting
Another problem which occurs is when we use a class such as araylist. We can store different types of objects in arraylist. But when we retrieve elements from arraylist then we need to use type conversion.
List list = new ArrayList(); list.add("1"); String s = (String) list.get(0);
If we use generic collection then casting is not required.Below code is same as the previous implementation but doesn’t need casting.
List<String> list = new ArrayList<String>(); list.add("1"); String s = list.get(0);
Leave a Reply