SlideShare a Scribd company logo
Generics and Collections
Visit http://gsbprogramming.blogspot.in
Generic programming is a style of computer programming in which algorithms are
written in terms of types to-be-specified-later that are then instantiated when
needed for specific types provided as parameters.
Generics are a facility of generic programming that were added to the Java
programming language in 2004 within version J2SE 5.0. They were designed to
extend Java's type system to allow “a type or method to operate on objects of
various types while providing compile-time type safety”
The Java collections framework supports generics to specify the type of objects
stored in a collection instance.
According to Java Language Specification:
1. A type variable is an unqualified identifier. Type variables are introduced by generic class
declarations, generic interface declarations, generic method declarations, and by generic
constructor declarations.
2. A class is generic if it declares one or more type variables. These type variables are known as the type
parameters of the class. It defines one or more type variables that act as parameters. A generic class
declaration defines a set of parameterized types, one for each possible invocation of the type
parameter section. All of these parameterized types share the same class at runtime.
3. An interface is generic if it declares one or more type variables. These type variables are known as the
type parameters of the interface. It defines one or more type variables that act as parameters. A
generic interface declaration defines a set of types, one for each possible invocation of the type
parameter section. All parameterized types share the same interface at runtime.
4. A method is generic if it declares one or more type variables. These type variables are known as the
formal type parameters of the method. The form of the formal type parameter list is identical to a type
parameter list of a class or interface.
5. A constructor can be declared as generic, independently of whether the class that the constructor is
declared in is itself generic. A constructor is generic if it declares one or more type variables. These
type variables are known as the formal type parameters of the constructor. The form of the formal
type parameter list is identical to a type parameter list of a generic class or interface.
Consider the following example:
Although the code is compiled without error, it throws a runtime exception (java.lang.ClassCastException) when
executing the second last statement of code. This type of problem can be avoided by using generics
With Generics:
Compiling this fragment with J2SE 5.0 (or later) will yield a compile-time error because the
compiler will detect that list.get(2) returns String instead of Integer
Entry<String, String> grade = new Entry<String, String>("Mike", "A");
Entry<String, Integer> mark = new Entry<String, Integer>("Mike", 100);
System.out.println("grade: " + grade);
System.out.println("mark: " + mark);
Entry<Integer, Boolean> prime =
new Entry<>(13, true); //Diamond Operator
if (prime.getValue())
System.out.println(prime.getKey() + " is prime.");
else
System.out.println(prime.getKey() + " is not prime.");
Output:
grade: (Mike, A)
mark: (Mike, 100)
13 is prime.
Note: If we remove the first <Type> in the above method, we will get compilation
error (cannot find symbol 'Type') since it represents the declaration of the symbol.
In many cases the user of the method need not indicate the type parameters, as
they can be inferred:
Entry<String, String> pair = Entry.twice("Hello");
The parameters can be explicitly added if needed:
Entry<String, String> pair = Entry.<String>twice("Hello");
Output:
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0
Programs that uses Generics has got many benefits over non-generic code.
1. Code Reuse: We can write a method/class/interface once and use for any type we want.
2. Type Safety : Generics make errors to appear compile time than at run time (It’s always
better to know problems in your code at compile time rather than making your code fail
at run time).
3. Individual Type Casting is not required
ArrayList <String> al= new ArrayList<String> ();
al.add(“Gurpreet");
// Typecasting is not needed
String s1 = al.get(0);
4. Implementing generic algorithms: By using generics, we can implement algorithms that
work on different types of objects and at the same they are type safe too.
What is Collection in java?
Collection represents a single unit of objects i.e. a group.
What is framework in java?
•provides readymade architecture.
•represents set of classes and interface.
•is optional.
What is Collection framework?
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
•Interfaces and its implementations i.e. classes
•Algorithm
Java ArrayList class uses a dynamic array for storing the elements. It inherits
AbstractList class and implements List interface.
The important points about Java ArrayList class are:
•Java ArrayList class can contain duplicate elements.
•Java ArrayList class maintains insertion order.
•Java ArrayList class is non synchronized.
•Java ArrayList allows random access because array works at the index basis.
•In Java ArrayList class, manipulation is slow because a lot of shifting needs to
be occurred if any element is removed from the array list.
Java LinkedList class uses doubly linked list to store the elements. It provides a
linked-list data structure. It inherits the AbstractList class and implements List
and Deque interfaces.
The important points about Java LinkedList are:
•Java LinkedList class can contain duplicate elements.
•Java LinkedList class maintains insertion order.
•Java LinkedList class is non synchronized.
•In Java LinkedList class, manipulation is fast because no shifting needs to
be occurred.
•Java LinkedList class can be used as list, stack or queue.
Java HashMap class implements the map interface by using a hashtable. It
inherits AbstractMap class and implements Map interface.
The important points about Java HashMap class are:
•A HashMap contains values based on the key.
•It contains only unique elements.
•It may have one null key and multiple null values.
•It maintains no order.
For more Visit:
http://gsb-programming.blogspot.in/search/label/Java

More Related Content

What's hot

Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 

What's hot (20)

Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Java collection
Java collectionJava collection
Java collection
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
07 java collection
07 java collection07 java collection
07 java collection
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 

Similar to Generics and collections in Java

Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
Raghu nath
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
Gaurav Maheshwari
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
yearninginjava
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
Ganesh Samarthyam
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
venud11
 

Similar to Generics and collections in Java (20)

Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Introduction
IntroductionIntroduction
Introduction
 
Core_Java_Interview.pdf
Core_Java_Interview.pdfCore_Java_Interview.pdf
Core_Java_Interview.pdf
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
 
JVM
JVMJVM
JVM
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2
 
Java notes
Java notesJava notes
Java notes
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Annotations
AnnotationsAnnotations
Annotations
 
Generics
GenericsGenerics
Generics
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
 

More from Gurpreet singh

More from Gurpreet singh (20)

Creating ESS Jobs for Oracle Fusion BIP Reports
Creating ESS Jobs for Oracle Fusion BIP ReportsCreating ESS Jobs for Oracle Fusion BIP Reports
Creating ESS Jobs for Oracle Fusion BIP Reports
 
Introduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP ReportingIntroduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP Reporting
 
Why Messaging system?
Why Messaging system?Why Messaging system?
Why Messaging system?
 
Understanding Flex Fields with Accounting Flexfields(Chart of Accounts) in O...
Understanding Flex Fields with  Accounting Flexfields(Chart of Accounts) in O...Understanding Flex Fields with  Accounting Flexfields(Chart of Accounts) in O...
Understanding Flex Fields with Accounting Flexfields(Chart of Accounts) in O...
 
Oracle Application Developmenr Framework
Oracle Application Developmenr FrameworkOracle Application Developmenr Framework
Oracle Application Developmenr Framework
 
Java Servlet part 3
Java Servlet part 3Java Servlet part 3
Java Servlet part 3
 
Oracle advanced queuing
Oracle advanced queuingOracle advanced queuing
Oracle advanced queuing
 
Oracle SQL Part 3
Oracle SQL Part 3Oracle SQL Part 3
Oracle SQL Part 3
 
Oracle SQL Part 2
Oracle SQL Part 2Oracle SQL Part 2
Oracle SQL Part 2
 
Oracle SQL Part1
Oracle SQL Part1Oracle SQL Part1
Oracle SQL Part1
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
 
Java Servlets Part 2
Java Servlets Part 2Java Servlets Part 2
Java Servlets Part 2
 
Creating business group in oracle apps
Creating business group in oracle appsCreating business group in oracle apps
Creating business group in oracle apps
 
Defing locations in Oracle Apps
Defing locations in Oracle AppsDefing locations in Oracle Apps
Defing locations in Oracle Apps
 
Assigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYSTAssigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYST
 
PL/SQL Part 5
PL/SQL Part 5PL/SQL Part 5
PL/SQL Part 5
 
PL/SQL Part 3
PL/SQL Part 3PL/SQL Part 3
PL/SQL Part 3
 
PL/SQL Part 2
PL/SQL Part 2PL/SQL Part 2
PL/SQL Part 2
 
PL/SQL Part 1
PL/SQL Part 1PL/SQL Part 1
PL/SQL Part 1
 
Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)
 

Recently uploaded

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 

Generics and collections in Java

  • 1. Generics and Collections Visit http://gsbprogramming.blogspot.in
  • 2. Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety” The Java collections framework supports generics to specify the type of objects stored in a collection instance.
  • 3. According to Java Language Specification: 1. A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations. 2. A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime. 3. An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime. 4. A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface. 5. A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface.
  • 4. Consider the following example: Although the code is compiled without error, it throws a runtime exception (java.lang.ClassCastException) when executing the second last statement of code. This type of problem can be avoided by using generics
  • 5. With Generics: Compiling this fragment with J2SE 5.0 (or later) will yield a compile-time error because the compiler will detect that list.get(2) returns String instead of Integer
  • 6. Entry<String, String> grade = new Entry<String, String>("Mike", "A"); Entry<String, Integer> mark = new Entry<String, Integer>("Mike", 100); System.out.println("grade: " + grade); System.out.println("mark: " + mark); Entry<Integer, Boolean> prime = new Entry<>(13, true); //Diamond Operator if (prime.getValue()) System.out.println(prime.getKey() + " is prime."); else System.out.println(prime.getKey() + " is not prime."); Output: grade: (Mike, A) mark: (Mike, 100) 13 is prime.
  • 7. Note: If we remove the first <Type> in the above method, we will get compilation error (cannot find symbol 'Type') since it represents the declaration of the symbol. In many cases the user of the method need not indicate the type parameters, as they can be inferred: Entry<String, String> pair = Entry.twice("Hello"); The parameters can be explicitly added if needed: Entry<String, String> pair = Entry.<String>twice("Hello");
  • 8. Output: java.lang.Integer = 11 java.lang.String = GeeksForGeeks java.lang.Double = 1.0
  • 9. Programs that uses Generics has got many benefits over non-generic code. 1. Code Reuse: We can write a method/class/interface once and use for any type we want. 2. Type Safety : Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time). 3. Individual Type Casting is not required ArrayList <String> al= new ArrayList<String> (); al.add(“Gurpreet"); // Typecasting is not needed String s1 = al.get(0); 4. Implementing generic algorithms: By using generics, we can implement algorithms that work on different types of objects and at the same they are type safe too.
  • 10. What is Collection in java? Collection represents a single unit of objects i.e. a group. What is framework in java? •provides readymade architecture. •represents set of classes and interface. •is optional. What is Collection framework? Collection framework represents a unified architecture for storing and manipulating group of objects. It has: •Interfaces and its implementations i.e. classes •Algorithm
  • 11.
  • 12. Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface. The important points about Java ArrayList class are: •Java ArrayList class can contain duplicate elements. •Java ArrayList class maintains insertion order. •Java ArrayList class is non synchronized. •Java ArrayList allows random access because array works at the index basis. •In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.
  • 13.
  • 14. Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces. The important points about Java LinkedList are: •Java LinkedList class can contain duplicate elements. •Java LinkedList class maintains insertion order. •Java LinkedList class is non synchronized. •In Java LinkedList class, manipulation is fast because no shifting needs to be occurred. •Java LinkedList class can be used as list, stack or queue.
  • 15.
  • 16.
  • 17. Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map interface. The important points about Java HashMap class are: •A HashMap contains values based on the key. •It contains only unique elements. •It may have one null key and multiple null values. •It maintains no order.
  • 18.