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

PDF
6 ways to hack your JavaScript application by Viktor Turskyi
PPTX
Java peresentation new soft
PDF
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
PPTX
Writing Test Cases with PHPUnit
PPT
Introduction to Intermediate Java
PPTX
OCEJPA(1Z0-898) Preparation Tips
PPTX
Exceptional Handling in Java
PPTX
JPA lifecycle events practice
6 ways to hack your JavaScript application by Viktor Turskyi
Java peresentation new soft
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
Writing Test Cases with PHPUnit
Introduction to Intermediate Java
OCEJPA(1Z0-898) Preparation Tips
Exceptional Handling in Java
JPA lifecycle events practice

What's hot (14)

PDF
Effective Java Second Edition
PPS
Java Exception handling
PPTX
Android Training (Java Review)
PPTX
Exceptions handling in java
PPT
C# Exceptions Handling
PPTX
Headless fragments in Android
PPTX
Presentation1
PPTX
Chapter 9.1
PPTX
Error and exception in python
PPT
CLR Exception Handing And Memory Management
ODP
Android tutorials7 calculator_packageexploirer
PDF
Exception handling
PPTX
Exceptions and errors in Java
PPTX
Exception handling
Effective Java Second Edition
Java Exception handling
Android Training (Java Review)
Exceptions handling in java
C# Exceptions Handling
Headless fragments in Android
Presentation1
Chapter 9.1
Error and exception in python
CLR Exception Handing And Memory Management
Android tutorials7 calculator_packageexploirer
Exception handling
Exceptions and errors in Java
Exception handling
Ad

Similar to Generics in java (20)

PDF
Javase5generics
PPT
Generic programming in java
PPTX
Generic Collections and learn how to use it
PDF
Generics and collections in Java
PDF
"Odisha's Living Legacy: Culture & Art".
PDF
08-L19-Generics.pdfGenerics Module 2.pptx
PPT
Java Generics for Dummies
PDF
Introducing generic types
ODP
javasebeyondbasics
PDF
Java Generics - by Example
PDF
Java Generics - by Example
PPT
Effective Java - Generics
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
PDF
JAVA Collection and generics
PPTX
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
PPT
Generic
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
PDF
On Parameterised Types and Java Generics
PDF
On Java Generics, History, Use, Caveats v1.1
Javase5generics
Generic programming in java
Generic Collections and learn how to use it
Generics and collections in Java
"Odisha's Living Legacy: Culture & Art".
08-L19-Generics.pdfGenerics Module 2.pptx
Java Generics for Dummies
Introducing generic types
javasebeyondbasics
Java Generics - by Example
Java Generics - by Example
Effective Java - Generics
Java Generics Introduction - Syntax Advantages and Pitfalls
JAVA Collection and generics
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
Generic
Generic Types in Java (for ArtClub @ArtBrains Software)
On Parameterised Types and Java Generics
On Java Generics, History, Use, Caveats v1.1
Ad

Recently uploaded (20)

PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPT
Mechanical Engineering MATERIALS Selection
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Welding lecture in detail for understanding
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Well-logging-methods_new................
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Mechanical Engineering MATERIALS Selection
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Foundation to blockchain - A guide to Blockchain Tech
Welding lecture in detail for understanding
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
OOP with Java - Java Introduction (Basics)
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Model Code of Practice - Construction Work - 21102022 .pdf
Internet of Things (IOT) - A guide to understanding
bas. eng. economics group 4 presentation 1.pptx
Well-logging-methods_new................
Automation-in-Manufacturing-Chapter-Introduction.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.}}