Java Generics
Java Generics
Java Generics
Why Generics?
Generics forces the developer to add only specific objects to the collection
to avoid runtime exception while casting.
For example:
List list = new ArrayList(); //Before generics
list.add(test); //adding data of String type to arraylist
list.add(new Dog()); //new method
list.add(Demo);//adding string type data to arraylist
Display(List list){
String str1=(String)list.get(0);
String str2=(String)list.get(1); //very Dangerous ClassCastException-Runtime exception
String str3=(String)list.get(2);
}
List<String > list = new ArrayList<String>();
list.add(test);
list.add(new Dog());
list.add(Demo);
import java.util.ArrayList;
public class Generics {
public static void main(String[] args) {
ArrayList<String> nums = new ArrayList<String>();
nums.add("One");
nums.add("Two");
nums.add("Three");
for(String s : nums){
int i = nums.indexOf(s);
System.out.println(i+" = "+s);
}
}
}
Generic Classes:
A generic class declaration looks like a non-generic class declaration,
except that the class name is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can
have one or more type parameters separated by commas. These classes are
known as parameterized classes or parameterized types because they
accept one or more parameters.
Example:
Following example illustrates how we can define a generic class: