Before Generics......was introduced..
You can't restrict the collections to accept only of a particular type.
You can't force an array list to contain only strings...
Example:
---------
If you say List multi = new ArrayList().
You can add..any type of objects.It may be String object or Dog object or House object... That means... you can't force the list to contain only... strings or dogs or house....
Problems
-----------
1)You can't force list or any collection to contain only of specific type.
Suppose...you created a arraylist...to store only string objects.
List stringsOnlyList = new ArrayList();
stringsOnlyList.add("Anil"); //It is fine as "Anil" is a string
Eventhough you want to add only strings in to stringsOnlyList.,Still we or some one can add
any type of object knowingly or unknowingly
stringsOnlyList .add(new Dog());
/// Here eventhough..you intented to add only
// strings... some other code in your project may unknowingly add non string
// object to list.
2)Unnecessary casting is required even when you know that.. list contains only
of particular type
Assume you know that you have added only strings to stringsOnlyList,eventhough
you have to typecast to String object because.. get method returns Object type.
String s = (String)stringsOnlyList.get(0);
Generics solves above problems
1)It solves the first problem by allowing the syntax to provide the type of the objects
you intend to add in to collection or list.
How to specify the type of the collection you intend to add in to collection ?
----------------------------------------------------------------------------
// Following is the pregenerics syntax.Here you can't force the collection to contain
//only strings
List stringsOnlyList = new ArrayList();
With generics.. you can force the above collection to contain only Strings.
You have to specify the type in angular brackets.
Eg:
List<String> stringsOnlyList = new ArrayList<String>();
So,now only string objects can be added in to stringsOnlyList.If you try to
add any non string objects compiler will give you error.
stringsOnlyList.add(new Dog());///Compiler won't allow and give you an error.
Eg2:If you want to add only Student Objects in to arraylist.
Just specify Student in angular brackets.Compiler will make sure that only
Student objects get added in to list.
List<Student> studentList = new ArrayList<Student>();
2 )Now... there is no need to typecast
You can simply assign returned string to String reference
String st = studentList.get(0);
For your reference following is the code before pregenerics..
Even though you know that stringsOnlyList contains strings still
we need to typecast to String.
String s = (String)stringsOnlyList.get(0);
The reason.. you need not add cast..in generics code is compiler will add necessary
cast for you...It just converts
String st = studentList.get(0);
into
String s = (String)stringsOnlyList.get(0);
Eg2:
Student st = studentList.get(0); // no need to cast the returned object to Student
because compiler does that when you compile the code..
What do you call the thing we are providing in <> ?
-----------------------------------------------------
We can call it as parameterized type or type parameter or type.
3)You can enhanced for loop to iterate collections with generics syntax.
Very easy right... ? No need to create iterator and call iterate method and also
no need to cast... to String.
Question:
If I declare the list to be of type Animal, can I add Animal subclass objects in to that list
List<Animal> aList = new ArrayList<Animal>();
With the above syntax...
1)You can add Animal class objects
or
2)Any Animal subclass objects.
Eg:Dog or Elephant.. objects
****Note:
Eventhough... Any subclass objects... of Animal can be added to list... Still
you need to make sure that type(Animal) is same both on left hand side
and right hand side...
Ex: List<Animal> aList = new ArrayList<Dog>();//// This is wrong...... because
of the above point
Question 2:
What is the generic syntax to make the collection accept any type of objects.
List<Object> multiList = new ArrayList<Object>();
Now you can add any type of object in to list. because as I said... you can add any object
which extends object.As you know every class extends object class,so we can add
any class object with the above syntax.
How to design Generic Class ?
------------------------------------------------
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package genericspro;
/**
*
* @author Rishitha
*/
public class MyGenericClass<T> {
private T instVar;
public T getInstVar() {
return instVar;
}
public void setInstVar(T instVar) {
this.instVar = instVar;
}
public static void main(String args[]){
MyGenericClass<String> insta = new MyGenericClass<String>();
insta.setInstVar("hello");
String getVal = insta.getInstVar();
System.out.println(getVal);
MyGenericClass<Integer> instaInt = new MyGenericClass<Integer>();
instaInt.setInstVar(1);
Integer getValInt = instaInt.getInstVar();
System.out.println(getValInt);
}
}
Explanation:
-------------
Whenever you see syntax.. like following...
public class MyGenericClass<T>
Just imagine that T will be replaced with the type you specify in angle brackets
while creating the instance..
Eg1:MyGenericClass<String> insta = new MyGenericClass<String>();
As you specified String as type,T will be replaced with String...That means
T in get and set methods will become
String getInstVar()
&
public void setInstVar(String instVar)
Eg2:MyGenericClass<Integer> insta = new MyGenericClass<Integer>();
As you specified Integer as type,T will be replaced with Integer...That means
T in get and set methods will become
Integer getInstVar()
&
public void setInstVar(Integer instVar)
So MyGenericClass behaves as an instance variable declared with String type
or Integer type.
In the above example I declared type as <T>,it need not be T.You can specify E or F
or any legal java identifier.
Let us see ArrayList api with generics syntax...
------------------------------------------------
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
So,when you say
List<String> listIn = new ArrayList<String>();
When you compile the code,the compiler will replaceAll E with String...
So,your set methods and get methods just behave as if you have declared
with String type...
You can't restrict the collections to accept only of a particular type.
You can't force an array list to contain only strings...
Example:
---------
If you say List multi = new ArrayList().
You can add..any type of objects.It may be String object or Dog object or House object... That means... you can't force the list to contain only... strings or dogs or house....
Problems
-----------
1)You can't force list or any collection to contain only of specific type.
Suppose...you created a arraylist...to store only string objects.
List stringsOnlyList = new ArrayList();
stringsOnlyList.add("Anil"); //It is fine as "Anil" is a string
Eventhough you want to add only strings in to stringsOnlyList.,Still we or some one can add
any type of object knowingly or unknowingly
stringsOnlyList .add(new Dog());
/// Here eventhough..you intented to add only
// strings... some other code in your project may unknowingly add non string
// object to list.
2)Unnecessary casting is required even when you know that.. list contains only
of particular type
Assume you know that you have added only strings to stringsOnlyList,eventhough
you have to typecast to String object because.. get method returns Object type.
String s = (String)stringsOnlyList.get(0);
Generics solves above problems
1)It solves the first problem by allowing the syntax to provide the type of the objects
you intend to add in to collection or list.
How to specify the type of the collection you intend to add in to collection ?
----------------------------------------------------------------------------
// Following is the pregenerics syntax.Here you can't force the collection to contain
//only strings
List stringsOnlyList = new ArrayList();
With generics.. you can force the above collection to contain only Strings.
You have to specify the type in angular brackets.
Eg:
List<String> stringsOnlyList = new ArrayList<String>();
So,now only string objects can be added in to stringsOnlyList.If you try to
add any non string objects compiler will give you error.
stringsOnlyList.add(new Dog());///Compiler won't allow and give you an error.
Eg2:If you want to add only Student Objects in to arraylist.
Just specify Student in angular brackets.Compiler will make sure that only
Student objects get added in to list.
List<Student> studentList = new ArrayList<Student>();
2 )Now... there is no need to typecast
You can simply assign returned string to String reference
String st = studentList.get(0);
For your reference following is the code before pregenerics..
Even though you know that stringsOnlyList contains strings still
we need to typecast to String.
String s = (String)stringsOnlyList.get(0);
The reason.. you need not add cast..in generics code is compiler will add necessary
cast for you...It just converts
String st = studentList.get(0);
into
String s = (String)stringsOnlyList.get(0);
Eg2:
Student st = studentList.get(0); // no need to cast the returned object to Student
because compiler does that when you compile the code..
What do you call the thing we are providing in <> ?
-----------------------------------------------------
We can call it as parameterized type or type parameter or type.
3)You can enhanced for loop to iterate collections with generics syntax.
for (String s : studentList) {
System.out.println(s);
}
Very easy right... ? No need to create iterator and call iterate method and also
no need to cast... to String.
Question:
If I declare the list to be of type Animal, can I add Animal subclass objects in to that list
List<Animal> aList = new ArrayList<Animal>();
With the above syntax...
1)You can add Animal class objects
or
2)Any Animal subclass objects.
Eg:Dog or Elephant.. objects
****Note:
Eventhough... Any subclass objects... of Animal can be added to list... Still
you need to make sure that type(Animal) is same both on left hand side
and right hand side...
Ex: List<Animal> aList = new ArrayList<Dog>();//// This is wrong...... because
of the above point
Question 2:
What is the generic syntax to make the collection accept any type of objects.
List<Object> multiList = new ArrayList<Object>();
Now you can add any type of object in to list. because as I said... you can add any object
which extends object.As you know every class extends object class,so we can add
any class object with the above syntax.
How to design Generic Class ?
------------------------------------------------
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package genericspro;
/**
*
* @author Rishitha
*/
public class MyGenericClass<T> {
private T instVar;
public T getInstVar() {
return instVar;
}
public void setInstVar(T instVar) {
this.instVar = instVar;
}
public static void main(String args[]){
MyGenericClass<String> insta = new MyGenericClass<String>();
insta.setInstVar("hello");
String getVal = insta.getInstVar();
System.out.println(getVal);
MyGenericClass<Integer> instaInt = new MyGenericClass<Integer>();
instaInt.setInstVar(1);
Integer getValInt = instaInt.getInstVar();
System.out.println(getValInt);
}
}
Explanation:
-------------
Whenever you see syntax.. like following...
public class MyGenericClass<T>
Just imagine that T will be replaced with the type you specify in angle brackets
while creating the instance..
Eg1:MyGenericClass<String> insta = new MyGenericClass<String>();
As you specified String as type,T will be replaced with String...That means
T in get and set methods will become
String getInstVar()
&
public void setInstVar(String instVar)
Eg2:MyGenericClass<Integer> insta = new MyGenericClass<Integer>();
As you specified Integer as type,T will be replaced with Integer...That means
T in get and set methods will become
Integer getInstVar()
&
public void setInstVar(Integer instVar)
So MyGenericClass behaves as an instance variable declared with String type
or Integer type.
In the above example I declared type as <T>,it need not be T.You can specify E or F
or any legal java identifier.
Let us see ArrayList api with generics syntax...
------------------------------------------------
public class ArrayList<E>
Now let us see one very important syntax in Generics:
|
sort(List<T> list)
Sorts the specified list into ascending order, according to the natural ordering of its elements. |
T extends Comparable means
Any class that Implements comparable can be passed to sort method.
If the class doesn't implement comparable code wont' compile.
Only List with the objects that implement Comparable interface are
eligible for sorting...
Do following example:
Create a student class
with sid and sname
Create 2 student objects and add to ArrayList
and try to call Collections.sort.. you will get compilation error.
Create 2 student objects and add to ArrayList
and try to call Collections.sort... you won't get error
because String implements comparable interface
No comments:
Post a Comment