SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in javaVishnu Suresh
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programmingRiccardo Cardin
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptxvishal choudhary
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
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...Edureka!
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Introduction to Java 11
Introduction to Java 11 Introduction to Java 11
Introduction to Java 11 Knoldus Inc.
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 

La actualidad más candente (20)

Wrapper class
Wrapper classWrapper class
Wrapper class
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Files in java
Files in javaFiles in java
Files in java
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
Generics
GenericsGenerics
Generics
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
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...
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Introduction to Java 11
Introduction to Java 11 Introduction to Java 11
Introduction to Java 11
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 

Similar a Java Generics and Collections Framework

Similar a Java Generics and Collections Framework (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
 

Más 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
 

Más 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

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Último (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Java Generics and Collections Framework

  • 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.