SlideShare a Scribd company logo
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by
detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the java
programmer to store a specific type of objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other
objects.
Without Generics, we can store any type of objects.
1. List list = new ArrayList();
2. list.add(10);
3. list.add("10");
4. With Generics, it is required to specify the type of object we need to store.
5. List<Integer> list = new ArrayList<Integer>();
6. list.add(10);
7. list.add("10");// compile-time error
2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
1. List list = new ArrayList();
2. list.add("hello");
3. String s = (String) list.get(0);//typecasting
4. After Generics, we don't need to typecast the object.
5. List<String> list = new ArrayList<String>();
6. list.add("hello");
7. String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The
good programming strategy says it is far better to handle the problem at compile time than runtime.
1. List<String> list = new ArrayList<String>();
2. list.add("hello");
3. list.add(32);//Compile Time Error
Syntax to use generic collection
1. ClassOrInterface<Type>
Example to use Generics in java
1. ArrayList<String>
Full Example of Generics in Java
Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.
1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10.System.out.println("element is: "+s);
11.
12.Iterator<String> itr=list.iterator();
13.while(itr.hasNext()){
14.System.out.println(itr.next());
15.}
16.}
17.}
1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10.System.out.println("element is: "+s);
11.
12.Iterator<String> itr=list.iterator();
13.while(itr.hasNext()){
14.System.out.println(itr.next());
15.}
16.}
17.}
Example of Java Generics using Map
Now we are going to use map elements using generics. Here, we need to pass key and value. Let us
understand it by a simple example:
1. import java.util.*;
2. class TestGenerics2{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(1,"vijay");
6. map.put(4,"umesh");
7. map.put(2,"ankit");
8.
9. //Now use Map.Entry for Set and Iterator
10.Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12.Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13.while(itr.hasNext()){
14.Map.Entry e=itr.next();//no need to typecast
15.System.out.println(e.getKey()+" "+e.getValue());
16.}
17.
18.}}

More Related Content

What's hot

Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Editionlosalamos
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
Khaled Anaqwa
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
sharqiyem
 
Headless fragments in Android
Headless fragments in AndroidHeadless fragments in Android
Headless fragments in Android
Ali Muzaffar
 
Presentation1
Presentation1Presentation1
Presentation1
Anul Chaudhary
 
Chapter 9.1
Chapter 9.1Chapter 9.1
Chapter 9.1sotlsoc
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
junnubabu
 
CLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementCLR Exception Handing And Memory Management
CLR Exception Handing And Memory Management
Shiny Zhu
 
Android tutorials7 calculator_packageexploirer
Android tutorials7 calculator_packageexploirerAndroid tutorials7 calculator_packageexploirer
Android tutorials7 calculator_packageexploirerVlad Kolesnyk
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
Manuela Grindei
 

What's hot (14)

Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Edition
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Headless fragments in Android
Headless fragments in AndroidHeadless fragments in Android
Headless fragments in Android
 
Presentation1
Presentation1Presentation1
Presentation1
 
Chapter 9.1
Chapter 9.1Chapter 9.1
Chapter 9.1
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
CLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementCLR Exception Handing And Memory Management
CLR Exception Handing And Memory Management
 
Android tutorials7 calculator_packageexploirer
Android tutorials7 calculator_packageexploirerAndroid tutorials7 calculator_packageexploirer
Android tutorials7 calculator_packageexploirer
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
Exception handling
Exception handlingException handling
Exception handling
 

Similar to Generics in java

Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Javase5generics
Javase5genericsJavase5generics
Javase5genericsimypraz
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
Roshan Deniyage
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
talha ijaz
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor56
 
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptxJAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
fwzmypc2004
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
Surendar Meesala
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
AKR Education
 
Java Array String
Java Array StringJava Array String
Java Array String
Manish Tiwari
 
Java 9 features
Java 9 featuresJava 9 features
Java 9 features
shrinath97
 
Icom4015 lecture15-f16
Icom4015 lecture15-f16Icom4015 lecture15-f16
Icom4015 lecture15-f16
BienvenidoVelezUPR
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
SURBHI SAROHA
 
GenericsFinal.ppt
GenericsFinal.pptGenericsFinal.ppt
GenericsFinal.ppt
Virat10366
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 

Similar to Generics in java (20)

Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Collections
CollectionsCollections
Collections
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptxJAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Java Array String
Java Array StringJava Array String
Java Array String
 
Java 9 features
Java 9 featuresJava 9 features
Java 9 features
 
Icom4015 lecture15-f16
Icom4015 lecture15-f16Icom4015 lecture15-f16
Icom4015 lecture15-f16
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Java generics final
Java generics finalJava generics final
Java generics final
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
 
GenericsFinal.ppt
GenericsFinal.pptGenericsFinal.ppt
GenericsFinal.ppt
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 

Recently uploaded

14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 

Recently uploaded (20)

14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 

Generics in java

  • 1. Generics in Java The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the java programmer to store a specific type of objects. Advantage of Java Generics There are mainly 3 advantages of generics. They are as follows: 1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other objects. Without Generics, we can store any type of objects. 1. List list = new ArrayList(); 2. list.add(10); 3. list.add("10"); 4. With Generics, it is required to specify the type of object we need to store. 5. List<Integer> list = new ArrayList<Integer>(); 6. list.add(10); 7. list.add("10");// compile-time error 2) Type casting is not required: There is no need to typecast the object. Before Generics, we need to type cast. 1. List list = new ArrayList(); 2. list.add("hello"); 3. String s = (String) list.get(0);//typecasting 4. After Generics, we don't need to typecast the object. 5. List<String> list = new ArrayList<String>(); 6. list.add("hello"); 7. String s = list.get(0); 3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime. 1. List<String> list = new ArrayList<String>(); 2. list.add("hello"); 3. list.add(32);//Compile Time Error Syntax to use generic collection 1. ClassOrInterface<Type> Example to use Generics in java 1. ArrayList<String> Full Example of Generics in Java Here, we are using the ArrayList class, but you can use any collection class such as ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc. 1. import java.util.*; 2. class TestGenerics1{ 3. public static void main(String args[]){ 4. ArrayList<String> list=new ArrayList<String>(); 5. list.add("rahul"); 6. list.add("jai"); 7. //list.add(32);//compile time error 8. 9. String s=list.get(1);//type casting is not required 10.System.out.println("element is: "+s); 11.
  • 2. 12.Iterator<String> itr=list.iterator(); 13.while(itr.hasNext()){ 14.System.out.println(itr.next()); 15.} 16.} 17.} 1. import java.util.*; 2. class TestGenerics1{ 3. public static void main(String args[]){ 4. ArrayList<String> list=new ArrayList<String>(); 5. list.add("rahul"); 6. list.add("jai"); 7. //list.add(32);//compile time error 8. 9. String s=list.get(1);//type casting is not required 10.System.out.println("element is: "+s); 11. 12.Iterator<String> itr=list.iterator(); 13.while(itr.hasNext()){ 14.System.out.println(itr.next()); 15.} 16.} 17.} Example of Java Generics using Map Now we are going to use map elements using generics. Here, we need to pass key and value. Let us understand it by a simple example: 1. import java.util.*; 2. class TestGenerics2{ 3. public static void main(String args[]){ 4. Map<Integer,String> map=new HashMap<Integer,String>(); 5. map.put(1,"vijay"); 6. map.put(4,"umesh"); 7. map.put(2,"ankit"); 8. 9. //Now use Map.Entry for Set and Iterator 10.Set<Map.Entry<Integer,String>> set=map.entrySet(); 11. 12.Iterator<Map.Entry<Integer,String>> itr=set.iterator(); 13.while(itr.hasNext()){ 14.Map.Entry e=itr.next();//no need to typecast 15.System.out.println(e.getKey()+" "+e.getValue()); 16.} 17. 18.}}