SlideShare uma empresa Scribd logo
1 de 19
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEdureka!
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work pptRanjith Alappadan
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introductionSohanur63
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionPritom Chaki
 

Mais procurados (20)

Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Java collections
Java collectionsJava collections
Java collections
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
Java Collections
Java  Collections Java  Collections
Java Collections
 

Semelhante a Generics and collections in Java

Semelhante a 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
 

Mais de Gurpreet singh

Introduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP ReportingIntroduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP ReportingGurpreet singh
 
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...Gurpreet singh
 
Oracle Application Developmenr Framework
Oracle Application Developmenr FrameworkOracle Application Developmenr Framework
Oracle Application Developmenr FrameworkGurpreet singh
 
Oracle advanced queuing
Oracle advanced queuingOracle advanced queuing
Oracle advanced queuingGurpreet singh
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingGurpreet singh
 
Creating business group in oracle apps
Creating business group in oracle appsCreating business group in oracle apps
Creating business group in oracle appsGurpreet singh
 
Defing locations in Oracle Apps
Defing locations in Oracle AppsDefing locations in Oracle Apps
Defing locations in Oracle AppsGurpreet singh
 
Assigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYSTAssigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYSTGurpreet singh
 
Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)Gurpreet singh
 
Ingenium test(Exam Management System) Project Presentation (Full)
Ingenium test(Exam Management System) Project Presentation (Full)Ingenium test(Exam Management System) Project Presentation (Full)
Ingenium test(Exam Management System) Project Presentation (Full)Gurpreet singh
 

Mais de Gurpreet singh (20)

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)
 
Ingenium test(Exam Management System) Project Presentation (Full)
Ingenium test(Exam Management System) Project Presentation (Full)Ingenium test(Exam Management System) Project Presentation (Full)
Ingenium test(Exam Management System) Project Presentation (Full)
 

Último

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 

Último (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

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.