Generics in java have been added from java1.5, Even you don't know about generics if you have worked on collection framework in java, i am sure you should have used generics. It is possible to genirify the methods and classes in java. In this tutorial we are going to discuss about how the generics are used in java how to write generic methods and classes, lets begin with the generics in collections.
Generics in collections:
Generics provides compile time type checking and to avoid the risk of class cast exception at run time, generic information will be lost at run time, JVM doesn't know the generic information at run time.
Let's discuss with an example, non generic collection can hold any type of object.
List myList = new ArrayList();
myList.add("bobby");//adding string object
myList.add("fred");//adding string object
myList.add(new Integer(12)); //adding ineteger object
here you can add any type of object that doesn't complain,While retrieving the object from the collection,
String myString = (String)myList.get(0);
in this case cast fails at run time when we try to retrieve the integer object from the collection. So we must do two things for non generics case
1. it is the programmer responsibility to save a correct object type into collections
2. while retrieving the programmer needs to do explicit cast.
same code with generics:
List<String> myList = new ArrayList<String>();
myList.add("bobby");//adding string object
myList.add("fred");//adding string object
myList.add(new Integer(12)); // gives the compiler error you can't add any object other than String.
So now using generics in collections,
1. it is the compiler responsibility to check and save a correct object type into collections
2. while retrieving the programmer need not do explicit cast.
Generics in classes:
We can declare our class as generic type. A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.
Example: public class GenericClass<T> {
T t;
public GenericClass(T t) {
this.t = t;
}
public static void main(String[] args) {
GenericClass<Animal> at = new GenericClass<Animal>(new Animal());
GenericClass<Box> bt = new GenericClass<Box>(new Box());
System.out.println(at.t);
System.out.println(bt.t);
}
}
class Animal {
@Override
public String toString() {
// TODO Auto-generated method stub
return "Animal class";
}
}
class Box {
@Override
public String toString() {
// TODO Auto-generated method stub
return "Box class";
}
}
output: Animal class
Box class
Generics in Methods:
If we don't want to use the generics in the whole class, then we can use generics method in the class.
Example:
public class GenericMethodAddItem {
public static void main(String[] args) {
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<String> strings = new ArrayList<String>();
GenericMethodAddItem gma = new GenericMethodAddItem();
gma.addItem(2, ints);//auto boxing works here.
gma.addItem("Raju", strings);
for(Integer item : ints){
System.out.println(item);
}
for(String item : strings){
System.out.println(item);
}
}
//add t item to the T list type.
public <T> void addItem(T t,ArrayList<T> collection){
collection.add(t);
}
}
in the above example int item is added to Integer array list and string item is added String array list.
Look at once the syntax of the method. here we used angular bracket with T(i.e <T>) T specifies the type.
for example in the above code, if you try to modify the following line as
gma.addItem(1, strings);
then the compiler will give you the compile time error. We cannot add int to String array list.
Usage of Super,extend,Wild card(?) in generic methods:
As we know that in java we can assign sub type object to super type like this.
Animal animal; //super type
Fox fox; //subtype
animal = new Fox();// assign sub class object to super class reference. No problem
Now:
ArrayList<Animal> animalList = new ArrayList<Animal>();
ArrayList<Fox> foxlList = new ArrayList<Fox>();
animalList = foxList;// We can't do this gives you the compiler error.
Here is a simple examples:
public class GenericMethodAddItem {
public static void main(String[] args) {
ArrayList<Animals> animalList = new ArrayList<Animals>();
animalList.add(new Animals());
ArrayList<Fox> foxList = new ArrayList<Fox>();
foxList.add(new Fox());
GenericMethodAddItem gmi = new GenericMethodAddItem();
gmi.addItem(animalList);
//gmi.addItem(foxlList); shows the compiler error.
//even Animals is a super type, in Animal list we cannot add sub type objects.
}
public <T> void addItem(ArrayList<Animals> listObjects){
for(int i=0;i<listObjects.size();i++){
System.out.println(listObjects.get(i));
}
}
}
class Animals {
public void print(){
System.out.println("i am animal");
}
}
class Fox extends Animals {
public void print(){
System.out.println("i am fox");
}
}
So in the above example, we cannot call the addItem() method with foxList as parameter. if we want make it work use wild card character as shown below.
i am changing the addItem method only:
public <T> void addItem(ArrayList<?> listObjects){
//listObjects.add(---) cannot add
for(int i=0;i<listObjects.size();i++){
System.out.println(listObjects.get(i));
}
}
now it will work for both animalList as well as foxList(super type and sub type).
In this case it will accept any type of list, this is know as Unbound wild card.
Generics in collections:
Generics provides compile time type checking and to avoid the risk of class cast exception at run time, generic information will be lost at run time, JVM doesn't know the generic information at run time.
Let's discuss with an example, non generic collection can hold any type of object.
List myList = new ArrayList();
myList.add("bobby");//adding string object
myList.add("fred");//adding string object
myList.add(new Integer(12)); //adding ineteger object
here you can add any type of object that doesn't complain,While retrieving the object from the collection,
String myString = (String)myList.get(0);
in this case cast fails at run time when we try to retrieve the integer object from the collection. So we must do two things for non generics case
1. it is the programmer responsibility to save a correct object type into collections
2. while retrieving the programmer needs to do explicit cast.
same code with generics:
List<String> myList = new ArrayList<String>();
myList.add("bobby");//adding string object
myList.add("fred");//adding string object
myList.add(new Integer(12)); // gives the compiler error you can't add any object other than String.
So now using generics in collections,
1. it is the compiler responsibility to check and save a correct object type into collections
2. while retrieving the programmer need not do explicit cast.
Generics in classes:
We can declare our class as generic type. A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.
Example: public class GenericClass<T> {
T t;
public GenericClass(T t) {
this.t = t;
}
public static void main(String[] args) {
GenericClass<Animal> at = new GenericClass<Animal>(new Animal());
GenericClass<Box> bt = new GenericClass<Box>(new Box());
System.out.println(at.t);
System.out.println(bt.t);
}
}
class Animal {
@Override
public String toString() {
// TODO Auto-generated method stub
return "Animal class";
}
}
class Box {
@Override
public String toString() {
// TODO Auto-generated method stub
return "Box class";
}
}
output: Animal class
Box class
Generics in Methods:
If we don't want to use the generics in the whole class, then we can use generics method in the class.
Example:
public class GenericMethodAddItem {
public static void main(String[] args) {
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<String> strings = new ArrayList<String>();
GenericMethodAddItem gma = new GenericMethodAddItem();
gma.addItem(2, ints);//auto boxing works here.
gma.addItem("Raju", strings);
for(Integer item : ints){
System.out.println(item);
}
for(String item : strings){
System.out.println(item);
}
}
//add t item to the T list type.
public <T> void addItem(T t,ArrayList<T> collection){
collection.add(t);
}
}
in the above example int item is added to Integer array list and string item is added String array list.
Look at once the syntax of the method. here we used angular bracket with T(i.e <T>) T specifies the type.
for example in the above code, if you try to modify the following line as
gma.addItem(1, strings);
then the compiler will give you the compile time error. We cannot add int to String array list.
Usage of Super,extend,Wild card(?) in generic methods:
As we know that in java we can assign sub type object to super type like this.
Animal animal; //super type
Fox fox; //subtype
animal = new Fox();// assign sub class object to super class reference. No problem
Now:
ArrayList<Animal> animalList = new ArrayList<Animal>();
ArrayList<Fox> foxlList = new ArrayList<Fox>();
animalList = foxList;// We can't do this gives you the compiler error.
Here is a simple examples:
public class GenericMethodAddItem {
public static void main(String[] args) {
ArrayList<Animals> animalList = new ArrayList<Animals>();
animalList.add(new Animals());
ArrayList<Fox> foxList = new ArrayList<Fox>();
foxList.add(new Fox());
GenericMethodAddItem gmi = new GenericMethodAddItem();
gmi.addItem(animalList);
//gmi.addItem(foxlList); shows the compiler error.
//even Animals is a super type, in Animal list we cannot add sub type objects.
}
public <T> void addItem(ArrayList<Animals> listObjects){
for(int i=0;i<listObjects.size();i++){
System.out.println(listObjects.get(i));
}
}
}
class Animals {
public void print(){
System.out.println("i am animal");
}
}
class Fox extends Animals {
public void print(){
System.out.println("i am fox");
}
}
So in the above example, we cannot call the addItem() method with foxList as parameter. if we want make it work use wild card character as shown below.
i am changing the addItem method only:
public <T> void addItem(ArrayList<?> listObjects){
//listObjects.add(---) cannot add
for(int i=0;i<listObjects.size();i++){
System.out.println(listObjects.get(i));
}
}
now it will work for both animalList as well as foxList(super type and sub type).
In this case it will accept any type of list, this is know as Unbound wild card.
use of extends or upperbound wild card:
example:
public <T> void addItem(ArrayList<? extends Animal> listObjects){
//listObjects.add(---) cannot add
for(int i=0;i<listObjects.size();i++){
System.out.println(listObjects.get(i));
}
}
In this case only sub type of Animals or Animals can invoke this method. so we can call this way.
gmi.addItem(foxList);
here the foxList is the list of Fox objects and Fox is the sub class of Animals.
example2:
if we want to add numbers and return sum. The numbers may be int or float or double or long.
So we can write generic method as follows:
As we know that Number is the super type of Integer,float,double,long.
public <T> int addItem(ArrayList<? extends Number> listObjects){
int sum =0;
for(int i=0;i<listObjects.size();i++){
sum = sum+listObjects.get(i);
}
return sum;
}
so you can invoke the above method like this:
1. addItem(longList);
2. addItem(integerList);
3. addItem(floatList);
4. addItem(doubleList);
To simply say that, in place of ? any type that must be subtype of Number would accept.
Use of Super or Lowerbound:
In case of Unbound and Upperbound wildcard usage, we cannot add any new item to list in the generic method. That line has commented out in both the examples. So if we want to add an item in the list in the generic method, we must use the Super keyword as follows.
for(int i=0;i<listObjects.size();i++){
System.out.println(listObjects.get(i));
}
}
for(int i=0;i<listObjects.size();i++){
System.out.println(listObjects.get(i));
}
}
In this case only sub type of Animals or Animals can invoke this method. so we can call this way.
gmi.addItem(foxList);
here the foxList is the list of Fox objects and Fox is the sub class of Animals.
example2:
if we want to add numbers and return sum. The numbers may be int or float or double or long.
So we can write generic method as follows:
As we know that Number is the super type of Integer,float,double,long.
public <T> int addItem(ArrayList<? extends Number> listObjects){
int sum =0;
for(int i=0;i<listObjects.size();i++){
sum = sum+listObjects.get(i);
}
return sum;
}
so you can invoke the above method like this:
1. addItem(longList);
2. addItem(integerList);
3. addItem(floatList);
4. addItem(doubleList);
To simply say that, in place of ? any type that must be subtype of Number would accept.
Use of Super or Lowerbound:
In case of Unbound and Upperbound wildcard usage, we cannot add any new item to list in the generic method. That line has commented out in both the examples. So if we want to add an item in the list in the generic method, we must use the Super keyword as follows.
public <T> void addItem(ArrayList<? super Fox> listObjects){
listObjects.add(new Fox()) for(int i=0;i<listObjects.size();i++){
System.out.println(listObjects.get(i));
}
}
we call this method like this:
addItem(animalList);
here the animalList contains the Animal objects and Animal is the super type of Fox.
addItem(animalList);
here the animalList contains the Animal objects and Animal is the super type of Fox.
No comments:
Post a Comment