Generics in Java
Generics in Java
JDK 5 introduce the Generic feature in java. it's very important for type-safe objects.Before generics feature, we can store any type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects.
Generics mainly focus Type-Safety,Type Casting
1- Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
2- Type casting is not required: There is no need to typecast the object.
List list = new ArrayList();
list.add("Mindclues");
String s = (String) list.get(0);//typecasting
But after generic no need for type casting.
List<String> list = new ArrayList<String>();
list.add("Mindclues");
String s = list.get(0);//no need typecasting
3- Compile-Time Checking:
It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.
This feature is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, collection classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of generic class, we use following syntax.
// To create an instance of generic class BaseType <Type> obj = new BaseType <Type>() Note: In Parameter type we can not use primitives like 'int','char' or 'double'.
Java Generic Type
Java Generic Type Naming convention helps us understanding code easily and having a naming convention is one of the best practices of java programming language. So generics also comes with it’s own naming conventions. Usually type parameter names are single, uppercase letters to make it easily distinguishable from java variables. The most commonly used type parameter names are:
- E – Element (used extensively by the Java Collections Framework, for example ArrayList, Set etc.)
- K – Key (Used in Map)
- N – Number
- T – Type
- V – Value (Used in Map)
- S,U,V etc. – 2nd, 3rd, 4th types
post a comment