Java 5 features | part 1 Generics
Hello ,
Today we will discuss about the Generics in java 4/5 features.
Generics are used to deal with type-safe feature.
It is used to make our code very stable it detects the bugs in runtime environment.
Before generics, we can store any type of data type in the collection.
But after generics we have to specify the data type to store the data in collection.
Here collections refers to hashmap, arraylist, ...
Before generics:
List list = new ArrayList();
list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to store.
After generics:
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
Advantages:
1. Type-safety
2. Type casting is not required
3. compile time error check
Generic class:
A class is refers to any datatype is know as generic class
creating a generic class:
class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
Comments
Post a Comment