SlideShare uma empresa Scribd logo
1 de 30
JAVA ESSENTIAL TRAINING



            Collections

                                     Linh LeVan
                           lelinh2302@gmail.com
                 http://tinhocbk123.appspot.com



                                                  1
&
VC
     BB
          Objects




          List            Set




                    Map

                                2
&
VC
     BB
           Introduction to java.util package

      The java.util package contains the definition of a
       number of useful classes providing a broad range of
       functionality
      Collections Framework belongs to this package. It
       consists of interfaces and classes for working with
       group of objects.




                                                         3
&
VC
     BB
           Collection

     Collection is nothing but group of similar data.
     It provides us an API to work with data
      structures such as trees, lists, sets, maps, arrays
      etc.
     Collections allow us to add, retrieve update or
      delete a set of objects (CRUD operations).




                                                        4
&
VC
     BB
            Array vs Collection

      Array
        o Holds objects of known type.
        o Fixed size
      Collections
        o Generalization of the array concept.
        o Set of interfaces defined in Java for storing
          object.
        o Multiple types of objects.
        o Resizable.

                                                          5
&
VC
     BB
           Collection Interfaces

      Collections are primarily defined through a set
      of interfaces.
      Supported by a set of classes that implement
      the interfaces




                                                         6
&
VC
     BB
                Some methods of “Collection” interface -1


     o int size()
          Returns the number of elements in this collection.
     o boolean isEmpty()
          Returns true if this collection contains no elements.
     o boolean contains(Object element)
          Returns true if this collection contains the specified element
     o boolean add(Object element)
          Ensures that this collection contains the specified element

     o Iterator iterator()
          Returns an iterator over the elements in this collection.


                                                                           7
&
VC
     BB
           Iterator (1)

      An iterator is an object that allows to traverse
       through all the elements of a collection,
       regardless of its specific implementation
      An iterator is sometimes called a cursor
      No need for index




                                                          8
&
VC
     BB
          Iterator (2)


          Collection collection = ...;
         Iterator it= collection.iterator();
         while (it.hasNext()) {
                Object   element = it.next();
                // Do    something with element
         }




                                                  9
&
VC
     BB
          List interface
      The List interface is an extension of the
       Collection interface.
      It defines an ordered collection of data and
       allows duplicate objects to be added to a list.
      The List interface uses an index for ordering
       the elements while storing them in a list. List
       has methods that allow access to elements
       based on their position.
      List has three different implementations:
       Vector, ArrayList, LinkedList
                                                     10
&
VC
     BB
               Common methods of List

     Access to elements via indexes, like arrays
           add (int, Object), get(int), remove(int), set(int, Object)

     Search for elements
           indexOf(Object), lastIndexOf(Object)

     Specialized
             Iterator, call ListIterator

     Extraction of sublist
             subList(int fromIndex, int toIndex)




                                                                         11
&
VC
     BB
           Implementation of List

     List has three different implementations:
        Vector
        ArrayList
        LinkedList




                                                  12
&
VC
     BB
            ArrayList

      Implements List interface
      Can grow and shrink dynamically.
      Unsynchronized.
      Values will be stored in the same order as inserted.
      Cannot store primitive values such as double
      Is best suited for random access without add and
       remove operations




                                                              13
&
VC
     BB
           Vector

      The Vector class is similar to an ArrayList as it
       also implements dynamic array
     Vector is synchronized; multiple threads
      cannot access the vector object concurrently.
      Only one thread can access the Vector object at
      a specific time.
     Values will be stored in the same order as
      inserted.



                                                           14
&
VC
     BB
           LinkedList

     LinkedList uses linked list data structure
      internally i.e. it uses nodes.
     LinkedList stores values randomly.
     LinkedList elements can be accessed
      sequentially only.
     It consumes lot of memory.
     Duplicate values are allowed.
     LinkedList is not synchronized.


                                                   15
&
VC
     BB
             LinkedList

 Common methods:
      •   addFirst(E obj)
      •   addLast(E obj)
      •   getFirst()
      •   getLast()
      •   removeFirst()
      •   removeLast()
 Gives better performance on add and remove vs
  ArrayList
 Gives poorer performance on get and set vs ArrayList


                                                         16
&
VC
     BB
              Set interface

     Corresponds to the mathematical definition of a
      set
           The Set interface creates a list of unordered objects.
           No duplicates are allowed
     Compared to the Collection interface
           Interface is identical.
           Every constructor must create a collection without
            duplicates.
           The operation add cannot add an element already in the
            set.
           The method call set1.equals(set2) works at follows

                                                                     17
&
VC
     BB
           Set classes

      HashSet class implements the Set interface, a
       HashSet creates a collection that makes use of a
       hash table for data storage
      LinkHashSet class creates a list of elements and
       maintains the order of elements added to the Set
      TreeSet class implements the Set interface and
       uses the tree structure for data storage. Objects are
       stored in ascending order




                                                           18
&
VC
     BB
          Set Idioms




                       19
&
VC
     BB
          Map interface

 A map is an object which stores key/value pairs.
 Both key and value are objects.
 Given a key, you can find its value.
 The keys must be unique, but you can have duplicate values.
 Some maps allow null keys and null values, others do not.
 There are 4 different implementations.
    TreeMap.
    HashMap.
    LinkedHashMap.
    HashTable

                                                         20
&
VC
     BB
              Some methods

      Methods for adding and deleting
        put(Object key, Object value)
           remove (Object key)
      Methods for extraction objects
           get (Object key)
      Methods to retrieve the keys, the values, and (key,
       value) pairs
           keySet() // returns its set of keys
           values() // returns a Collection of values
           entrySet() // returns a set of entry

                                                             21
&
VC
     BB
          Implementions of Map Interface

      There are 4 different implementations.
         TreeMap.
         HashMap.
         LinkedHashMap.
         HashTable




                                                22
&
VC
     BB
           TreeMap

     TreeMap can store key/value pairs.
     TreeMap uses tree data structure to store the
      keys.
     The keys are stored in sorted order.
     Null keys are not allowed but null values are
      allowed.
     Different types of keys are not allowed but
      different types of values are allowed.
     TreeMap is not synchronized.

                                                      23
&
VC
     BB
           HashMap

     HashMap can store key/value pairs.
     HashMap uses hashing mechanism to store the
      keys.
     The keys will be in unsorted order.
     Null keys and null values are allowed.
     Different types of keys and values are allowed.
     HashMap is not synchronized.



                                                        24
&
VC
     BB
           LinkedHashMap

     LinkedHashMap can store key/value pairs.
     LinkedHashMap uses hashing mechanism to
      store the keys.
     The keys will be in stored in the same order as
      inserted but are unsorted.
     Null keys and null values are allowed.
     Different types of keys and values are allowed.
     LinkedHashMap is not synchronized.


                                                        25
&
VC
     BB
           HashTable

     HashTable is a legacy class.
     HashTable can store key/value pairs.
     HashTable uses hashing mechanism to store
      the keys.
     The keys will be unsorted.
     Null keys and null values are not allowed.
     Different types of keys and values are allowed.
     HashTable is synchronized.


                                                        26
&
VC
     BB
           Traversal Interfaces

     Collection framework also provides 3 interfaces
      to traverse the elements or objects within the
      collection:
        Enumeration
        Iterator
        ListIterator




                                                        27
&
VC
     BB
          Enumeration

     Can be used with only legacy classes(this is
      introduced in java 1.0).
     Using this interface, we can traverse only in
      forward direction.
     In this process performance is very slow.
     The supported methods are hasMoreElements(),
      nextElement().




                                                  28
&
VC
     BB
           Iterator

     Can be used with all classes of Collection.
     It is introduced in java 1.2.
     It is better than Enumeration in performance.
     It provides more functionalities than
      Enumeration.
     The supported methods are hasNext(), next(),
      remove().



                                                      29
&
VC
     BB
           ListIterator

     Can only be used with classes which implement
      List interface.(Vector, ArrayList and LinkedList).
     It is introduced in java 1.2.
     The supported methods are hasNext(), next(),
      hasPrevious(), previous(), remove(), add().
     This interface provides the
      best performance and functionality.
     We can traverse bidirectionally by using this
      interface.

                                                       30

Mais conteúdo relacionado

Mais procurados

5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
java collections
java collectionsjava collections
java collectionsjaveed_mhd
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)SURBHI SAROHA
 
Java collections
Java collectionsJava collections
Java collectionspadmad2291
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialMarcus Biel
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryGauravPatil318
 
Java Collection
Java CollectionJava Collection
Java CollectionDeeptiJava
 

Mais procurados (20)

5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
20 ch22 collections
20 ch22 collections20 ch22 collections
20 ch22 collections
 
java collections
java collectionsjava collections
java collections
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
Collections framework
Collections frameworkCollections framework
Collections framework
 
Java collection
Java collectionJava collection
Java collection
 
Java collections
Java collectionsJava collections
Java collections
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video Tutorial
 
Collada Reference Card 1.4
Collada Reference Card 1.4Collada Reference Card 1.4
Collada Reference Card 1.4
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
 

Destaque

Undangan Pernikahan Unik Murah - Nazli & Zadli
Undangan Pernikahan Unik Murah - Nazli & ZadliUndangan Pernikahan Unik Murah - Nazli & Zadli
Undangan Pernikahan Unik Murah - Nazli & ZadliKlik Desain
 
Collectn framework
Collectn frameworkCollectn framework
Collectn frameworkcharan kumar
 
Winter 1071 student english arabic vocabulary list
Winter 1071 student english arabic vocabulary listWinter 1071 student english arabic vocabulary list
Winter 1071 student english arabic vocabulary listScott Dagilis
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreadingayman diab
 
5 engaging tactics to optimise conversions for your email marketing progra
5 engaging tactics to optimise conversions for your email marketing progra5 engaging tactics to optimise conversions for your email marketing progra
5 engaging tactics to optimise conversions for your email marketing prograHolistic Email Marketing
 
7 tips to getting your subscribers to action your emails
7 tips to getting your subscribers to action your emails7 tips to getting your subscribers to action your emails
7 tips to getting your subscribers to action your emailsHolistic Email Marketing
 
Սառցե լուսանկարներ
Սառցե լուսանկարներՍառցե լուսանկարներ
Սառցե լուսանկարներMartin Atoyan
 
Decomposition, combustion, detonation,_synthetic,_analytical,_crystallographi...
Decomposition, combustion, detonation,_synthetic,_analytical,_crystallographi...Decomposition, combustion, detonation,_synthetic,_analytical,_crystallographi...
Decomposition, combustion, detonation,_synthetic,_analytical,_crystallographi...uedalab
 
Treat Cyber Like a Disease
Treat Cyber Like a DiseaseTreat Cyber Like a Disease
Treat Cyber Like a DiseaseSurfWatch Labs
 
Apache Hadoop Summit 2016: The Future of Apache Hadoop an Enterprise Architec...
Apache Hadoop Summit 2016: The Future of Apache Hadoop an Enterprise Architec...Apache Hadoop Summit 2016: The Future of Apache Hadoop an Enterprise Architec...
Apache Hadoop Summit 2016: The Future of Apache Hadoop an Enterprise Architec...PwC
 
FERMA European Risk and Insurance Report (ERIR) 2016
FERMA European Risk and Insurance Report (ERIR) 2016FERMA European Risk and Insurance Report (ERIR) 2016
FERMA European Risk and Insurance Report (ERIR) 2016FERMA
 
World Economic Forum: The power of analytics for better and faster decisions ...
World Economic Forum: The power of analytics for better and faster decisions ...World Economic Forum: The power of analytics for better and faster decisions ...
World Economic Forum: The power of analytics for better and faster decisions ...PwC
 
Impact on e-commerce of the GDPR- Etrade Summit 2016
Impact on e-commerce of the GDPR- Etrade Summit 2016Impact on e-commerce of the GDPR- Etrade Summit 2016
Impact on e-commerce of the GDPR- Etrade Summit 2016Bart Van Den Brande
 

Destaque (17)

Best experiences
Best experiences Best experiences
Best experiences
 
Tarea seminario 5
Tarea seminario 5Tarea seminario 5
Tarea seminario 5
 
Undangan Pernikahan Unik Murah - Nazli & Zadli
Undangan Pernikahan Unik Murah - Nazli & ZadliUndangan Pernikahan Unik Murah - Nazli & Zadli
Undangan Pernikahan Unik Murah - Nazli & Zadli
 
Collectn framework
Collectn frameworkCollectn framework
Collectn framework
 
Winter 1071 student english arabic vocabulary list
Winter 1071 student english arabic vocabulary listWinter 1071 student english arabic vocabulary list
Winter 1071 student english arabic vocabulary list
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
5 engaging tactics to optimise conversions for your email marketing progra
5 engaging tactics to optimise conversions for your email marketing progra5 engaging tactics to optimise conversions for your email marketing progra
5 engaging tactics to optimise conversions for your email marketing progra
 
7 tips to getting your subscribers to action your emails
7 tips to getting your subscribers to action your emails7 tips to getting your subscribers to action your emails
7 tips to getting your subscribers to action your emails
 
Սառցե լուսանկարներ
Սառցե լուսանկարներՍառցե լուսանկարներ
Սառցե լուսանկարներ
 
Decomposition, combustion, detonation,_synthetic,_analytical,_crystallographi...
Decomposition, combustion, detonation,_synthetic,_analytical,_crystallographi...Decomposition, combustion, detonation,_synthetic,_analytical,_crystallographi...
Decomposition, combustion, detonation,_synthetic,_analytical,_crystallographi...
 
Legionowo
LegionowoLegionowo
Legionowo
 
Bridging tourism and education policies
Bridging tourism and education policiesBridging tourism and education policies
Bridging tourism and education policies
 
Treat Cyber Like a Disease
Treat Cyber Like a DiseaseTreat Cyber Like a Disease
Treat Cyber Like a Disease
 
Apache Hadoop Summit 2016: The Future of Apache Hadoop an Enterprise Architec...
Apache Hadoop Summit 2016: The Future of Apache Hadoop an Enterprise Architec...Apache Hadoop Summit 2016: The Future of Apache Hadoop an Enterprise Architec...
Apache Hadoop Summit 2016: The Future of Apache Hadoop an Enterprise Architec...
 
FERMA European Risk and Insurance Report (ERIR) 2016
FERMA European Risk and Insurance Report (ERIR) 2016FERMA European Risk and Insurance Report (ERIR) 2016
FERMA European Risk and Insurance Report (ERIR) 2016
 
World Economic Forum: The power of analytics for better and faster decisions ...
World Economic Forum: The power of analytics for better and faster decisions ...World Economic Forum: The power of analytics for better and faster decisions ...
World Economic Forum: The power of analytics for better and faster decisions ...
 
Impact on e-commerce of the GDPR- Etrade Summit 2016
Impact on e-commerce of the GDPR- Etrade Summit 2016Impact on e-commerce of the GDPR- Etrade Summit 2016
Impact on e-commerce of the GDPR- Etrade Summit 2016
 

Semelhante a Collections

Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxeyemitra1
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.pptNaitikChatterjee
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionssuseredfbe9
 
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...Sagar Verma
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections frameworkRavi Chythanya
 
Week_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfWeek_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfPrabhaK22
 
Java collections-interview-questions
Java collections-interview-questionsJava collections-interview-questions
Java collections-interview-questionsyearninginjava
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Collection framework
Collection frameworkCollection framework
Collection frameworkDilvarSingh2
 
Collections in java
Collections in javaCollections in java
Collections in javakejpretkopet
 

Semelhante a Collections (20)

Java collections
Java collectionsJava collections
Java collections
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
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...
 
Java util
Java utilJava util
Java util
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
Week_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfWeek_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdf
 
Java collections-interview-questions
Java collections-interview-questionsJava collections-interview-questions
Java collections-interview-questions
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Array list(1)
Array list(1)Array list(1)
Array list(1)
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
Collections
CollectionsCollections
Collections
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Collections
CollectionsCollections
Collections
 
Collections in java
Collections in javaCollections in java
Collections in java
 

Mais de Linh Lê

Nq bq-nd ro
Nq bq-nd roNq bq-nd ro
Nq bq-nd roLinh Lê
 
LAB - He thong ten mien (DNS)
LAB - He thong ten mien (DNS)LAB - He thong ten mien (DNS)
LAB - He thong ten mien (DNS)Linh Lê
 
Network Address Translation (NAT)
Network Address Translation (NAT)Network Address Translation (NAT)
Network Address Translation (NAT)Linh Lê
 
nslookup - Quan tri mang (2)
nslookup - Quan tri mang (2)nslookup - Quan tri mang (2)
nslookup - Quan tri mang (2)Linh Lê
 
Homework - C programming language
Homework - C programming languageHomework - C programming language
Homework - C programming languageLinh Lê
 
Access BaiGiang
Access BaiGiangAccess BaiGiang
Access BaiGiangLinh Lê
 
Kiểu cấu trúc và kiểu hợp
Kiểu cấu trúc và kiểu hợpKiểu cấu trúc và kiểu hợp
Kiểu cấu trúc và kiểu hợpLinh Lê
 
Các lệnh cơ bản
Các lệnh cơ bảnCác lệnh cơ bản
Các lệnh cơ bảnLinh Lê
 
Word 2007 Labs
Word 2007 LabsWord 2007 Labs
Word 2007 LabsLinh Lê
 
Kiểu mảng
Kiểu mảngKiểu mảng
Kiểu mảngLinh Lê
 
LTC-Cấu trúc rẽ nhánh
LTC-Cấu trúc rẽ nhánhLTC-Cấu trúc rẽ nhánh
LTC-Cấu trúc rẽ nhánhLinh Lê
 
Xâu kí tự
Xâu kí tựXâu kí tự
Xâu kí tựLinh Lê
 
Tong quan ve lap trinh
Tong quan ve lap trinhTong quan ve lap trinh
Tong quan ve lap trinhLinh Lê
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & InterfaceLinh Lê
 
Cấu trúc lặp (loop)
Cấu trúc lặp (loop)Cấu trúc lặp (loop)
Cấu trúc lặp (loop)Linh Lê
 
Hàm (function)
Hàm (function)Hàm (function)
Hàm (function)Linh Lê
 

Mais de Linh Lê (17)

Nq bq-nd ro
Nq bq-nd roNq bq-nd ro
Nq bq-nd ro
 
LAB - He thong ten mien (DNS)
LAB - He thong ten mien (DNS)LAB - He thong ten mien (DNS)
LAB - He thong ten mien (DNS)
 
Network Address Translation (NAT)
Network Address Translation (NAT)Network Address Translation (NAT)
Network Address Translation (NAT)
 
nslookup - Quan tri mang (2)
nslookup - Quan tri mang (2)nslookup - Quan tri mang (2)
nslookup - Quan tri mang (2)
 
Homework - C programming language
Homework - C programming languageHomework - C programming language
Homework - C programming language
 
Access BaiGiang
Access BaiGiangAccess BaiGiang
Access BaiGiang
 
LTC File
LTC FileLTC File
LTC File
 
Kiểu cấu trúc và kiểu hợp
Kiểu cấu trúc và kiểu hợpKiểu cấu trúc và kiểu hợp
Kiểu cấu trúc và kiểu hợp
 
Các lệnh cơ bản
Các lệnh cơ bảnCác lệnh cơ bản
Các lệnh cơ bản
 
Word 2007 Labs
Word 2007 LabsWord 2007 Labs
Word 2007 Labs
 
Kiểu mảng
Kiểu mảngKiểu mảng
Kiểu mảng
 
LTC-Cấu trúc rẽ nhánh
LTC-Cấu trúc rẽ nhánhLTC-Cấu trúc rẽ nhánh
LTC-Cấu trúc rẽ nhánh
 
Xâu kí tự
Xâu kí tựXâu kí tự
Xâu kí tự
 
Tong quan ve lap trinh
Tong quan ve lap trinhTong quan ve lap trinh
Tong quan ve lap trinh
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
 
Cấu trúc lặp (loop)
Cấu trúc lặp (loop)Cấu trúc lặp (loop)
Cấu trúc lặp (loop)
 
Hàm (function)
Hàm (function)Hàm (function)
Hàm (function)
 

Último

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
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.christianmathematics
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
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.pdfPoh-Sun Goh
 
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.pptxheathfieldcps1
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
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.docxRamakrishna Reddy Bijjam
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 

Último (20)

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
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.
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
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
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
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
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 

Collections

  • 1. JAVA ESSENTIAL TRAINING Collections Linh LeVan lelinh2302@gmail.com http://tinhocbk123.appspot.com 1
  • 2. & VC BB Objects List Set Map 2
  • 3. & VC BB Introduction to java.util package  The java.util package contains the definition of a number of useful classes providing a broad range of functionality  Collections Framework belongs to this package. It consists of interfaces and classes for working with group of objects. 3
  • 4. & VC BB Collection Collection is nothing but group of similar data. It provides us an API to work with data structures such as trees, lists, sets, maps, arrays etc. Collections allow us to add, retrieve update or delete a set of objects (CRUD operations). 4
  • 5. & VC BB Array vs Collection  Array o Holds objects of known type. o Fixed size  Collections o Generalization of the array concept. o Set of interfaces defined in Java for storing object. o Multiple types of objects. o Resizable. 5
  • 6. & VC BB Collection Interfaces  Collections are primarily defined through a set of interfaces.  Supported by a set of classes that implement the interfaces 6
  • 7. & VC BB Some methods of “Collection” interface -1 o int size() Returns the number of elements in this collection. o boolean isEmpty() Returns true if this collection contains no elements. o boolean contains(Object element) Returns true if this collection contains the specified element o boolean add(Object element) Ensures that this collection contains the specified element o Iterator iterator() Returns an iterator over the elements in this collection. 7
  • 8. & VC BB Iterator (1)  An iterator is an object that allows to traverse through all the elements of a collection, regardless of its specific implementation  An iterator is sometimes called a cursor  No need for index 8
  • 9. & VC BB Iterator (2) Collection collection = ...; Iterator it= collection.iterator(); while (it.hasNext()) { Object element = it.next(); // Do something with element } 9
  • 10. & VC BB List interface  The List interface is an extension of the Collection interface.  It defines an ordered collection of data and allows duplicate objects to be added to a list.  The List interface uses an index for ordering the elements while storing them in a list. List has methods that allow access to elements based on their position.  List has three different implementations: Vector, ArrayList, LinkedList 10
  • 11. & VC BB Common methods of List Access to elements via indexes, like arrays  add (int, Object), get(int), remove(int), set(int, Object) Search for elements  indexOf(Object), lastIndexOf(Object) Specialized  Iterator, call ListIterator Extraction of sublist  subList(int fromIndex, int toIndex) 11
  • 12. & VC BB Implementation of List List has three different implementations:  Vector  ArrayList  LinkedList 12
  • 13. & VC BB ArrayList  Implements List interface  Can grow and shrink dynamically.  Unsynchronized.  Values will be stored in the same order as inserted.  Cannot store primitive values such as double  Is best suited for random access without add and remove operations 13
  • 14. & VC BB Vector  The Vector class is similar to an ArrayList as it also implements dynamic array Vector is synchronized; multiple threads cannot access the vector object concurrently. Only one thread can access the Vector object at a specific time. Values will be stored in the same order as inserted. 14
  • 15. & VC BB LinkedList LinkedList uses linked list data structure internally i.e. it uses nodes. LinkedList stores values randomly. LinkedList elements can be accessed sequentially only. It consumes lot of memory. Duplicate values are allowed. LinkedList is not synchronized. 15
  • 16. & VC BB LinkedList  Common methods: • addFirst(E obj) • addLast(E obj) • getFirst() • getLast() • removeFirst() • removeLast()  Gives better performance on add and remove vs ArrayList  Gives poorer performance on get and set vs ArrayList 16
  • 17. & VC BB Set interface Corresponds to the mathematical definition of a set  The Set interface creates a list of unordered objects.  No duplicates are allowed Compared to the Collection interface  Interface is identical.  Every constructor must create a collection without duplicates.  The operation add cannot add an element already in the set.  The method call set1.equals(set2) works at follows 17
  • 18. & VC BB Set classes  HashSet class implements the Set interface, a HashSet creates a collection that makes use of a hash table for data storage  LinkHashSet class creates a list of elements and maintains the order of elements added to the Set  TreeSet class implements the Set interface and uses the tree structure for data storage. Objects are stored in ascending order 18
  • 19. & VC BB Set Idioms 19
  • 20. & VC BB Map interface  A map is an object which stores key/value pairs.  Both key and value are objects.  Given a key, you can find its value.  The keys must be unique, but you can have duplicate values.  Some maps allow null keys and null values, others do not.  There are 4 different implementations.  TreeMap.  HashMap.  LinkedHashMap.  HashTable 20
  • 21. & VC BB Some methods  Methods for adding and deleting  put(Object key, Object value)  remove (Object key)  Methods for extraction objects  get (Object key)  Methods to retrieve the keys, the values, and (key, value) pairs  keySet() // returns its set of keys  values() // returns a Collection of values  entrySet() // returns a set of entry 21
  • 22. & VC BB Implementions of Map Interface  There are 4 different implementations.  TreeMap.  HashMap.  LinkedHashMap.  HashTable 22
  • 23. & VC BB TreeMap TreeMap can store key/value pairs. TreeMap uses tree data structure to store the keys. The keys are stored in sorted order. Null keys are not allowed but null values are allowed. Different types of keys are not allowed but different types of values are allowed. TreeMap is not synchronized. 23
  • 24. & VC BB HashMap HashMap can store key/value pairs. HashMap uses hashing mechanism to store the keys. The keys will be in unsorted order. Null keys and null values are allowed. Different types of keys and values are allowed. HashMap is not synchronized. 24
  • 25. & VC BB LinkedHashMap LinkedHashMap can store key/value pairs. LinkedHashMap uses hashing mechanism to store the keys. The keys will be in stored in the same order as inserted but are unsorted. Null keys and null values are allowed. Different types of keys and values are allowed. LinkedHashMap is not synchronized. 25
  • 26. & VC BB HashTable HashTable is a legacy class. HashTable can store key/value pairs. HashTable uses hashing mechanism to store the keys. The keys will be unsorted. Null keys and null values are not allowed. Different types of keys and values are allowed. HashTable is synchronized. 26
  • 27. & VC BB Traversal Interfaces Collection framework also provides 3 interfaces to traverse the elements or objects within the collection:  Enumeration  Iterator  ListIterator 27
  • 28. & VC BB Enumeration Can be used with only legacy classes(this is introduced in java 1.0). Using this interface, we can traverse only in forward direction. In this process performance is very slow. The supported methods are hasMoreElements(), nextElement(). 28
  • 29. & VC BB Iterator Can be used with all classes of Collection. It is introduced in java 1.2. It is better than Enumeration in performance. It provides more functionalities than Enumeration. The supported methods are hasNext(), next(), remove(). 29
  • 30. & VC BB ListIterator Can only be used with classes which implement List interface.(Vector, ArrayList and LinkedList). It is introduced in java 1.2. The supported methods are hasNext(), next(), hasPrevious(), previous(), remove(), add(). This interface provides the best performance and functionality. We can traverse bidirectionally by using this interface. 30