Generics in Java | What is Generics in Java
-The Java Generics concept introduced in Java 5 to deal with type-safe objects.
Before Generics,programmers can store any type of objects in collection framework i.e., non-generics.
-Now Java Generics forces programmers to store specific type of objects.
Objective of Java Generics
-The Java Generics concept introduced in Java 5 to deal with type-safe objects.
Before Generics,programmers can store any type of objects in collection framework i.e., non-generics.
-Now Java Generics forces programmers to store specific type of objects.
Objective of Java Generics
- Type-Safety.
- To Remove Type Casting Problem.
Type Safety
Arrays are type safe i.e. we can give guarantee for the type of element present inside array.
For example:
If programmer requirement is to hold only String type of object then we can choose String Array ,by mistake if we are trying to insert any other type of object then we will get compile time error saying Type Mismatch.
String [] s=new String[10];
s[0]="The Tech Matin";
s[1]=new Integer(1);//here we will get compile time error saying //Type Mismatch:can not convert from Integer to String
Hence String Array can contain only String Type of Objects,due to this we can say Arrays are Type Safe.
- But Collection's are not Type Safe i.e. we can not give the guarantee for type of elements present inside Collection's.
Example:
If programmer requirement is to hold only String Type of Objects ,if we choose ArrayList and by mistake if we add any other type of objects then at that time we won't get any compile time error but the program will fail at Run Time.
- ArrayList al=new ArrayList();
- al.add("abc");
- al.add(new Integer(1));
- String s=(String)al.get(1);
- System.out.println(s);
- In the above example we are adding one String element and one Integer element.
- After adding element to ArrayList we are trying to get the element of 1st index and trying to hold it in String,here at line number 4 we will get compile time error saying Type Mismatch:can not convert from Object to String,because we don't know the type object,hence we need to do Type Casting.
- After type casting error will be resolved but at Run Time we will get Run Time Exception Saying :Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String.
To Overcome these problems SUN PEOPLE introduced Generic Concept in 1.5 Version.
Hence main objective of Java Generics are
- To provide Type Safety.
- To Resolve Type Casting Problem.
To hold only String type of Objects we can create Generics Version of ArrayList as shown Below.
- ArrayList<String> al=new ArrayList<String>();
- al.add("abc");
- al.add(new Integer(1));//
In the above ArrayList we can add only String Type of Objects,If we try to insert any other type of object then we will get Compile Time Error Saying At Line No. 3:The method add(String) in the type ArrayList<String> is not applicable for the arguments (Integer).
Hence through Generics we are getting Type Safety And Hence
String s=al.get(0);//No Type Casting
Type Casting Problem Also Resolved.
Full Example Of Generics In Java
public class GenDemo{
public static void main(String[] args) {
ArrayList<String> al=new ArrayList<String>();
al.add("The");
al.add("Tech");
al.add("Matin");
al.add(3);//comile time error
System.out.println(al.get(0)+" "+al.get(1)+" "+al.get(2));//No Type Casting Required :)
}//end of main
}//end of class
Main Advantage Of Java Generics
Full Example Of Generics In Java
public class GenDemo{
public static void main(String[] args) {
ArrayList<String> al=new ArrayList<String>();
al.add("The");
al.add("Tech");
al.add("Matin");
al.add(3);//comile time error
System.out.println(al.get(0)+" "+al.get(1)+" "+al.get(2));//No Type Casting Required :)
}//end of main
}//end of class
Main Advantage Of Java Generics
- Type Safety
- Type Casting is not required
- Compile Time Checking
Example of Java Generics Using Map
public class GenDemo {
public static void main(String[] args) {
Map<Integer, String> map=new HashMap<Integer, String>();
map.put(1,"Matin");
map.put(2,"Vijay");
map.put(3,"Darshan");
Set<Map.Entry<Integer, String>> set=map.entrySet();
Iterator<Map.Entry<Integer, String>> itr=set.iterator();
while(itr.hasNext()){
Map.Entry<Integer, String> data=itr.next();
System.out.println(data.getKey()+" "+data.getValue());
}//end of while
}//end of main
}//end of class
Generic Class
- A class that can refer to any type is known as Generic Class.
- Here we are using T type parameter to create a Generic Class.
- Let's see the example
Class TheTechMatin<T>{
T object;
void add(T object){
this.object=object;
}
T get(){
return object;
}
public static void main(String[] args) {
TheTechMatin<Integer> obj=new TheTechMatin<Integer>();
obj.add(3);
obj.add("Matin");//Compile Time Error
System.out.println(obj.get());
}//end of main
}//end of class
output: 3
Java Generics Type Parameters
The Type Parameter Naming Conventions are important to learn
Generics Thoroughly.
Common Type Parameter are as follows:
- T-Type
- E-Element
- K-Key
- N-Number
- V-Value
Generic Method
- Like Generic Class,we can create a Generic Method that can accept any type of argument.
- Let's see the simple example of Java Generic Method
public class MyClass{
public static <E> void printMyArray(E[] element){
for(E elements:element){
System.out.println(elements);
}
System.out.println();
}
public static void main(String[] args) {
Integer[] i= {1,2,3,4};
System.out.println("Printing Integers");
printMyArray(i);
String [] s= {"one","Two","Three","Four"};
System.out.println("Printing String");
printMyArray(s);
}
}
O/P
======
Printing Integers
1
2
3
4
Printing String
one
Two
Three
Four
WildCard in Java Generics
abstract class Alphabet{
abstract void methodName();
}
class A extends Alphabet{
@Override
void methodName() {
System.out.println("A Belongs To Alphabet");
}
}
class B extends Alphabet{
@Override
void methodName() {
System.out.println("B Belongs To Alphabet");
}
}
public class MyClass{
public static void readAlphabets(List<? extends Alphabet> list){
for(Alphabet lists:list){
lists.methodName();
}
}
public static void main(String args[]){
List<A> list1=new ArrayList<A>();
A a=new A();
list1.add(a);
List<B> list2=new ArrayList<B>();
B b=new B();
list2.add(b);
readAlphabets(list1);
readAlphabets(list2);
}//end of main
}//end of class
Out/Put:
A Belongs To Alphabet
B Belongs To Alphabet
Hope This Article Was Helpful.
O/P
======
Printing Integers
1
2
3
4
Printing String
one
Two
Three
Four
WildCard in Java Generics
- In Java Generics ?(Question mark) represent the wildcard element.
- It means any type.
- If we write <? extends Number> then,it means either Number or its Child Class.Ex Integer,Float,Double etc.
- Now we can call the methods of Number Class through any child class.
abstract class Alphabet{
abstract void methodName();
}
class A extends Alphabet{
@Override
void methodName() {
System.out.println("A Belongs To Alphabet");
}
}
class B extends Alphabet{
@Override
void methodName() {
System.out.println("B Belongs To Alphabet");
}
}
public class MyClass{
public static void readAlphabets(List<? extends Alphabet> list){
for(Alphabet lists:list){
lists.methodName();
}
}
public static void main(String args[]){
List<A> list1=new ArrayList<A>();
A a=new A();
list1.add(a);
List<B> list2=new ArrayList<B>();
B b=new B();
list2.add(b);
readAlphabets(list1);
readAlphabets(list2);
}//end of main
}//end of class
Out/Put:
A Belongs To Alphabet
B Belongs To Alphabet
Hope This Article Was Helpful.
awesome tutorial
ReplyDelete