SlideShare uma empresa Scribd logo
1 de 39
  Text-Based Application & Collection API
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Varargs With JDK 5.0 Java has included a feature that implifies the  creation of methods, that need to take variable number of arguments. This feature is called varargs and it short form for variable length  arguments. Prior to JDK5, variable length argument could be handled using arrays. Example  PassArray With variable length arguments A variable length argument is specified by three periods(…) To write a method using varargs static void vaTest (int …v)  Example  VarArgs
v is operated  as an array …  syntax simply tell the compiler that a variable number of arguments will be used. A method can have normal parameters along with variable length  parameters, however the variable length parameter must be last  parameter declared by the method. int doit(int a, int b, double c, int …vals) Overloading Vararg Methods Example  VarArgs2
String   is a sequence of characters. But, unlike many  other languages that implement strings as character arrays,  Java implements strings as objects of type  String . * Once a  String  object has been created, you cannot  change the characters that comprise that string. * Each time you need an altered version of an  existing string, a new  String  object is created that contains the modifications. The original string is  left unchanged.
* For those cases in which a modifiable string is desired,  there is a companion class to  String  called  StringBuffer ,  whose objects contain strings that can be modified after  they are created. * Both the  String  and  StringBuffer  classes are declared  final * The length of a string is the number of characters that it  contains. To obtain this value, call the  length( )  method, char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length());
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
// equals() vs == class EqualsNotEqualTo { public static void main(String args[]) { String s1 = "Hello"; String s2 = new String(s1); System.out.println(s1 + " equals " + s2 + "  " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + "  " + (s1 == s2)); } }
[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The core collection interfaces encapsulate different  types of collections, These interfaces allow collections to be manipulated independently of the details of  their representation.  A Set is a special kind of Collection.  A SortedSet is a special kind of Set.
The Collection interface is the least common  denominator that all collections implement  * The Java platform doesn't provide any direct  implementations of this interface but provides  implementations of more specific subinterfaces, such  as Set and List. Set  — a collection that cannot contain  duplicate   elements. This interface models the mathematical set  abstraction and is used to represent Sets.
List  — an ordered collection (sometimes called a  sequence ). Lists can contain duplicate elements. The user of a List  generally has precise control over where in the list each  element is inserted and can access elements by their integer  index (position). Queue  — a collection used to hold multiple elements  prior to processing. Besides basic Collection operations,  a Queue provides additional insertion, extraction,  and inspection operations. Map  — an object that maps keys to values. A Map cannot  contain duplicate keys: each key can map to at most one  value.
SortedSet  — a Set that maintains its elements in ascending  order. Sorted sets are used for naturally ordered sets. SortedMap  — a Map that maintains its mappings in  ascending key order. Implementation The classes that implement these interfaces are  listed below: Set  HashSet  TreeSet  LinkedHashSet List  Vector  ArrayList  LinkedList Map  HashMap  HashTable  TreeMap  LinkedHashMap SortedSet  TreeSet SortedMap   TreeMap
Interface and class hierarchy of collections
 
The ArrayList Class The ArrayList class extends AbstractList and implements the List  interface.  * ArrayList supports dynamic arrays that can grow as needed. * An  ArrayList  is a variable-length array of object references. * Since this implementation use an array to store the elements  of the list, so access to an element using an index is very fast. Example  ArrayListDemo.java Example  ArrayListToArray.java For obtaining an Array from an ArrayList.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Vector public class Vector extends AbstractList implements List. Vector is synchronized.  Vector constructors: Vector( ) The first form creates a default vector,which has an initial  size of 10.  Vector(int initialCapacity)   Constructs an empty vector with the specified initial  capacity and with its capacity increment equal to zero.  Vector(int initialCapacity, int capacityIncrement)              Constructs an empty vector with the specified initial  capacity and capacity increment.
Vector use an array to store the elements of the list; so  access to any element using an index is very fast.  Example  VectorDemo.java
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The TreeSet Class * Duplicate elements are not accepted. * TreeSet provides an implementation of the SortedSet  interface that uses a tree for storage. * This class guarantees that the sorted set will be in  ascending element order  * This implementation provides guaranteed log(n)  time cost for the basic operations . * Access and retrieval times are quite fast,which  makes  TreeSet  an excellent choice when storing large  amounts of sorted information that must be found quickly. * This implementation is not synchronized  *  The entries can be sorted using the Comparable interface.  Example  TreeSetDemo.java
HashMap HashMap implements Map and extends AbstractMap. * A hash map does  not  guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are  read by an iterator. * The HashMap class is roughly equivalent to Hashtable, except  that it is unsynchronized and permits nulls. *  This implementation is not synchronized. *  HashMap lets you have null values as well as one null key Example  HashMapDemo.java
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Hash Table * Like HashMap, Hashtable stores key/value pairs  in a hash table.  When using a Hashtable, you specify an object that is used  as a key, and the value that you want linked to that key. The key  is then hashed, and the resulting hash code is used as the index at  which the value is stored within the table. * A hash table can only store objects that override the  hashCode( ) and equals( ) methods that are defined by Object.  The hashCode( ) method must compute and return the hash code  for the object. * Hashtable is synchronized * Hashtable doesn't let you have anything that's null. Example  HTDemo.java
[object Object],[object Object],[object Object],[object Object],[object Object]
PriorityQueue  *  This class is new with Java 5.  * This class implements the Queue interface. * Since the LinkedList class has been enhanced to implement the  Queue interface, basic queues can be handled with a LinkedList.  * PriorityQueue create a "priority-in, priority out" queue as opposed  to a typical FIFO queue.  *A PriorityQueue's elements are ordered either by natural ordering  (in which case the elements that are sorted first will be accessed  first) or according to a Comparator.  * In either case, the elements' ordering represents their relative priority. * Queues have a few methods not found in other collection interfaces:  peek(), poll(), and offer().
Summary
 
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Generics Generics means parameterized types. Parameterized types are important as they enable to create classes, interfaces, and methods in which the type of data upon which they  operate is specified as parameter. Using Generics its possible to create a single class that automatically works with different types of data. The class, interface or methods that operate on a parameterized type is  called generic. Example  Gen, GenDemo
Generics eliminate the process to explicitly cast to translate between  Object and type of data being operated upon. Generics work only with Objects When declaring an instance of generic type, the type argument passed to the type parameter must be a class type. Gen<int> strOb=new Gen<int>(53);  // Error cannot use primitive.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Polymorphism and Generics Polymorphism applies to the &quot;base&quot; type of the collection: List<Integer> myList = new ArrayList<Integer>(); But what about this? List<Parent> myList = new ArrayList<Child>(); List<Number> numbers = new ArrayList<Integer>(); Is this possible? No, here—the type of the variable declaration must match  the type you pass to the actual object type.  If you declare  List<Foo> foo then whatever you assign to the  foo reference MUST be of the generic type <Foo>, Not a subtype  of <Foo>,Not a supertype of <Foo>, Just <Foo>.

Mais conteúdo relacionado

Mais procurados

Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 

Mais procurados (20)

Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java util
Java utilJava util
Java util
 
LectureNotes-05-DSA
LectureNotes-05-DSALectureNotes-05-DSA
LectureNotes-05-DSA
 
07 java collection
07 java collection07 java collection
07 java collection
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Generics
GenericsGenerics
Generics
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Collections framework
Collections frameworkCollections framework
Collections framework
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 

Destaque

Cubicaje ...(1)
Cubicaje ...(1)Cubicaje ...(1)
Cubicaje ...(1)
leidy95c
 
K leber teorias curriculares e suas implicações no ensino superior de música
K leber teorias curriculares e suas implicações no ensino superior de músicaK leber teorias curriculares e suas implicações no ensino superior de música
K leber teorias curriculares e suas implicações no ensino superior de música
Magali Kleber
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
Rakesh Madugula
 
Informa anual andalucía e inmigración 2010
Informa anual andalucía e inmigración 2010Informa anual andalucía e inmigración 2010
Informa anual andalucía e inmigración 2010
IntegraLocal
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
Md10 building java gu is
Md10 building java gu isMd10 building java gu is
Md10 building java gu is
Rakesh Madugula
 

Destaque (15)

Decreto2162de1983 minsalud
Decreto2162de1983 minsaludDecreto2162de1983 minsalud
Decreto2162de1983 minsalud
 
Cubicaje ...(1)
Cubicaje ...(1)Cubicaje ...(1)
Cubicaje ...(1)
 
From social data to social insight
From social data to social insightFrom social data to social insight
From social data to social insight
 
K leber teorias curriculares e suas implicações no ensino superior de música
K leber teorias curriculares e suas implicações no ensino superior de músicaK leber teorias curriculares e suas implicações no ensino superior de música
K leber teorias curriculares e suas implicações no ensino superior de música
 
Md11 gui event handling
Md11 gui event handlingMd11 gui event handling
Md11 gui event handling
 
Md121 streams
Md121 streamsMd121 streams
Md121 streams
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 
Desigualdadesocial
DesigualdadesocialDesigualdadesocial
Desigualdadesocial
 
Informa anual andalucía e inmigración 2010
Informa anual andalucía e inmigración 2010Informa anual andalucía e inmigración 2010
Informa anual andalucía e inmigración 2010
 
Recapitulacion federalismo v1
Recapitulacion federalismo v1Recapitulacion federalismo v1
Recapitulacion federalismo v1
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
Md10 building java gu is
Md10 building java gu isMd10 building java gu is
Md10 building java gu is
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 

Semelhante a Md08 collection api

Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
eyemitra1
 
Java collections
Java collectionsJava collections
Java collections
padmad2291
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
smile790243
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
phanleson
 

Semelhante a Md08 collection api (20)

collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Java.util
Java.utilJava.util
Java.util
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
String handling
String handlingString handling
String handling
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt
 
Array properties
Array propertiesArray properties
Array properties
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
Collection in Java
Collection in JavaCollection in Java
Collection in Java
 
Array list (java platform se 8 )
Array list (java platform se 8 )Array list (java platform se 8 )
Array list (java platform se 8 )
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Java collections
Java collectionsJava collections
Java collections
 
Java collections
Java collectionsJava collections
Java collections
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
 

Último

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Último (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 

Md08 collection api

  • 1. Text-Based Application & Collection API
  • 2.
  • 3.
  • 4.
  • 5. Varargs With JDK 5.0 Java has included a feature that implifies the creation of methods, that need to take variable number of arguments. This feature is called varargs and it short form for variable length arguments. Prior to JDK5, variable length argument could be handled using arrays. Example PassArray With variable length arguments A variable length argument is specified by three periods(…) To write a method using varargs static void vaTest (int …v) Example VarArgs
  • 6. v is operated as an array … syntax simply tell the compiler that a variable number of arguments will be used. A method can have normal parameters along with variable length parameters, however the variable length parameter must be last parameter declared by the method. int doit(int a, int b, double c, int …vals) Overloading Vararg Methods Example VarArgs2
  • 7. String is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String . * Once a String object has been created, you cannot change the characters that comprise that string. * Each time you need an altered version of an existing string, a new String object is created that contains the modifications. The original string is left unchanged.
  • 8. * For those cases in which a modifiable string is desired, there is a companion class to String called StringBuffer , whose objects contain strings that can be modified after they are created. * Both the String and StringBuffer classes are declared final * The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length());
  • 9.
  • 10. // equals() vs == class EqualsNotEqualTo { public static void main(String args[]) { String s1 = &quot;Hello&quot;; String s2 = new String(s1); System.out.println(s1 + &quot; equals &quot; + s2 + &quot; &quot; + s1.equals(s2)); System.out.println(s1 + &quot; == &quot; + s2 + &quot; &quot; + (s1 == s2)); } }
  • 11.
  • 12.
  • 13.
  • 14. The core collection interfaces encapsulate different types of collections, These interfaces allow collections to be manipulated independently of the details of their representation. A Set is a special kind of Collection. A SortedSet is a special kind of Set.
  • 15. The Collection interface is the least common denominator that all collections implement * The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List. Set — a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent Sets.
  • 16. List — an ordered collection (sometimes called a sequence ). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations. Map — an object that maps keys to values. A Map cannot contain duplicate keys: each key can map to at most one value.
  • 17. SortedSet — a Set that maintains its elements in ascending order. Sorted sets are used for naturally ordered sets. SortedMap — a Map that maintains its mappings in ascending key order. Implementation The classes that implement these interfaces are listed below: Set HashSet TreeSet LinkedHashSet List Vector ArrayList LinkedList Map HashMap HashTable TreeMap LinkedHashMap SortedSet TreeSet SortedMap TreeMap
  • 18. Interface and class hierarchy of collections
  • 19.  
  • 20. The ArrayList Class The ArrayList class extends AbstractList and implements the List interface. * ArrayList supports dynamic arrays that can grow as needed. * An ArrayList is a variable-length array of object references. * Since this implementation use an array to store the elements of the list, so access to an element using an index is very fast. Example ArrayListDemo.java Example ArrayListToArray.java For obtaining an Array from an ArrayList.
  • 21.
  • 22.
  • 23. Vector public class Vector extends AbstractList implements List. Vector is synchronized. Vector constructors: Vector( ) The first form creates a default vector,which has an initial size of 10. Vector(int initialCapacity)   Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. Vector(int initialCapacity, int capacityIncrement)            Constructs an empty vector with the specified initial capacity and capacity increment.
  • 24. Vector use an array to store the elements of the list; so access to any element using an index is very fast. Example VectorDemo.java
  • 25.
  • 26.
  • 27. The TreeSet Class * Duplicate elements are not accepted. * TreeSet provides an implementation of the SortedSet interface that uses a tree for storage. * This class guarantees that the sorted set will be in ascending element order * This implementation provides guaranteed log(n) time cost for the basic operations . * Access and retrieval times are quite fast,which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. * This implementation is not synchronized * The entries can be sorted using the Comparable interface. Example TreeSetDemo.java
  • 28. HashMap HashMap implements Map and extends AbstractMap. * A hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator. * The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. * This implementation is not synchronized. * HashMap lets you have null values as well as one null key Example HashMapDemo.java
  • 29.
  • 30. Hash Table * Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. * A hash table can only store objects that override the hashCode( ) and equals( ) methods that are defined by Object. The hashCode( ) method must compute and return the hash code for the object. * Hashtable is synchronized * Hashtable doesn't let you have anything that's null. Example HTDemo.java
  • 31.
  • 32. PriorityQueue * This class is new with Java 5. * This class implements the Queue interface. * Since the LinkedList class has been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. * PriorityQueue create a &quot;priority-in, priority out&quot; queue as opposed to a typical FIFO queue. *A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. * In either case, the elements' ordering represents their relative priority. * Queues have a few methods not found in other collection interfaces: peek(), poll(), and offer().
  • 34.  
  • 35.
  • 36. Generics Generics means parameterized types. Parameterized types are important as they enable to create classes, interfaces, and methods in which the type of data upon which they operate is specified as parameter. Using Generics its possible to create a single class that automatically works with different types of data. The class, interface or methods that operate on a parameterized type is called generic. Example Gen, GenDemo
  • 37. Generics eliminate the process to explicitly cast to translate between Object and type of data being operated upon. Generics work only with Objects When declaring an instance of generic type, the type argument passed to the type parameter must be a class type. Gen<int> strOb=new Gen<int>(53); // Error cannot use primitive.
  • 38.
  • 39. Polymorphism and Generics Polymorphism applies to the &quot;base&quot; type of the collection: List<Integer> myList = new ArrayList<Integer>(); But what about this? List<Parent> myList = new ArrayList<Child>(); List<Number> numbers = new ArrayList<Integer>(); Is this possible? No, here—the type of the variable declaration must match the type you pass to the actual object type. If you declare List<Foo> foo then whatever you assign to the foo reference MUST be of the generic type <Foo>, Not a subtype of <Foo>,Not a supertype of <Foo>, Just <Foo>.