SlideShare a Scribd company logo
1 of 27
Download to read offline
Collections in Java
• Arrays
       n   Has special language support
• Iterators
       n   Iterator (i)
• Collections (also called containers)
       n   Collection (i)
       n   Set (i),
              u    HashSet (c), TreeSet (c)
       n   List (i),
              u    ArrayList (c), LinkedList (c)
       n   Map (i),
              u    HashMap (c), TreeMap (c)



OOP: Collections                                       1
Array
  • Most efficient way to hold references to objects.

              data       Car Car       Car           Car
            index         0    1   2    3    4   5    6    7



  • Advantages
        n    An array know the type it holds, i.e., compile-time type checking.
        n    An array know its size, i.e., ask for the length.
        n    An array can hold primitive types directly.
  • Disadvantages
        n    An array can only hold one type of objects (including primitives).
        n    Arrays are fixed size.

OOP: Collections                                                                  2
Array, Example
       class Car{};                      // minimal dummy class
       Car[] cars1;                      // null reference
       Car[] cars2 = new Car[10];        // null references

       for (int i = 0; i < cars2.length; i++)
          cars2[i] = new Car();

       // Aggregated initialization
       Car[] cars3 = {new Car(), new Car(), new Car(), new Car()};
       cars1 = {new Car(), new Car(), new Car()};




  • Helper class java.util.Arrays
        n    Search and sort: binarySearch(), sort()
        n    Comparison: equals()            (many overloaded)
        n    Instantiation: fill()           (many overloaded)
        n    Conversion:      asList()
OOP: Collections                                                     3
Overview of Collection
  • A collection is a group of data manipulate as a single object.
       Corresponds to a bag.

  • Insulate client programs from the implementation.
        n    array, linked list, hash table, balanced binary tree
  •    Like C++'s Standard Template Library (STL)
  •    Can grow as necessary.
  •    Contain only Objects (reference types).
  •    Heterogeneous.
  •    Can be made thread safe (concurrent access).
  •    Can be made not-modifiable.

OOP: Collections                                                     4
Collection Interfaces
  • Collections are primarily defined through a set of interfaces.
        n    Supported by a set of classes that implement the interfaces




                                                                   [Source: java.sun.com]

  • Interfaces are used of flexibility reasons
        n    Programs that uses an interface is not tightened to a specific
             implementation of a collection.
        n    It is easy to change or replace the underlying collection class with
             another (more efficient) class that implements the same interface.
OOP: Collections                                                                            5
Collection Interfaces and Classes




OOP: Collections                           [Source: bruceeckel.com]   6
The Iterator Interface
  • The idea: Select each element in a collection
        n    Hide the underlying collection


                      Collection                               Iterator
                                                     list
                    isEmpty()                               hasNext()
                    add()                                   next()
                    remove()                                remove()
                    ...




  • Iterators are fail-fast
        n    Exception thrown if collection is modified externally, i.e., not via the
             iterator (multi-threading).


OOP: Collections                                                                        7
The Iterator Interface, cont.
       // the interface definition
       Interface Iterator {
          boolean hasNext();
          Object next();          // note "one-way" traffic
          void remove();
       }



       // an example
       public static void main (String[] args){
          ArrayList cars = new ArrayList();
          for (int i = 0; i < 12; i++)
             cars.add (new Car());

             Iterator it = cats.iterator();
             while (it.hasNext())
                System.out.println ((Car)it.next());
       }


OOP: Collections                                              8
The Collection Interface
            public interface Collection {
                // Basic Operations
                int size();
                boolean isEmpty();
                boolean contains(Object element);
                boolean add(Object element);    // Optional
                boolean remove(Object element); // Optional
                Iterator iterator();

                   // Bulk Operations
                   boolean containsAll(Collection c);
                   boolean addAll(Collection c);    //   Optional
                   boolean removeAll(Collection c); //   Optional
                   boolean retainAll(Collection c); //   Optional
                   void clear();                    //   Optional

                   // Array Operations
                   Object[] toArray();
                   Object[] toArray(Object a[]);
            }

OOP: Collections                                                    9
The Set Interface
  • Corresponds to the mathematical definition of a set (no
       duplicates are allowed).

  • Compared to the Collection interface
        n    Interface is identical.
        n    Every constructor must create a collection without duplicates.
        n    The operation add cannot add an element already in the set.
        n    The method call set1.equals(set2) works at follows
               u   set1 ⊆ set2, and set2 ⊆ set1




OOP: Collections                                                              10
Set Idioms
  • set1 ∪ set2
        n    set1.addAll(set2)
  • set1 ∩ set2
        n    set1.retainAll(set2)
  • set1 − set2
        n    set1.removeAll(set2)




OOP: Collections                         11
HashSet and TreeSet Classes
  • HashSet and TreeSet implement the interface Set.

  • HashSet
        n    Implemented using a hash table.
        n    No ordering of elements.
        n    add, remove, and contains methods constant time complexity
             O(c).


  • TreeSet
        n    Implemented using a tree structure.
        n    Guarantees ordering of elements.
        n    add, remove, and contains methods logarithmic time complexity
             O(log (n)), where n is the number of elements in the set.

OOP: Collections                                                             12
HashSet, Example
 // [Source: java.sun.com]
 import java.util.*;
 public class FindDups {
     public static void main(String args[]){
         Set s = new HashSet();
         for (int i = 0; i < args.length; i++){
             if (!s.add(args[i]))
                 System.out.println("Duplicate detected: " +
                                      args[i]);
         }
         System.out.println(s.size() +
                         " distinct words detected: " +
                         s);
   }
 }




OOP: Collections                                               13
The List Interface
  • The List interface corresponds to an order group of elements.
       Duplicates are allowed.

  • Extensions compared to the Collection interface
        n    Access to elements via indexes, like arrays
               u   add (int, Object), get(int), remove(int),
                   set(int, Object) (note set = replace bad name for the method)
        n    Search for elements
               u   indexOf(Object), lastIndexOf(Object)
        n    Specialized Iterator, call ListIterator
        n    Extraction of sublist
               u   subList(int fromIndex, int toIndex)




OOP: Collections                                                                   14
The List Interface, cont.
  Further requirements compared to the Collection Interface
  • add(Object)adds at the end of the list.
  • remove(Object)removes at the start of the list.
  • list1.equals(list2)the ordering of the elements is
       taken into consideration.
  •    Extra requirements to the method hashCode.
        n    list1.equals(list2) implies that
             list1.hashCode()==list2.hashCode()




OOP: Collections                                              15
The List Interface, cont.
       public interface List extends Collection {
           // Positional Access
           Object get(int index);
           Object set(int index, Object element); // Optional
           void add(int index, Object element);    // Optional
           Object remove(int index);               // Optional
           abstract boolean addAll(int index, Collection c);
                                                  // Optional

                   // Search
                   int indexOf(Object o);
                   int lastIndexOf(Object o);

                   // Iteration
                   ListIterator listIterator();
                   ListIterator listIterator(int index);

                   // Range-view
                   List subList(int from, int to);
       }

OOP: Collections                                                 16
ArrayList and LinkedList Classes
  • The classes ArrayList and LinkedList implement the
       List interface.

  • ArrayList is an array based implementation where elements
       can be accessed directly via the get and set methods.
        n    Default choice for simple sequence.


  • LinkedList is based on a double linked list
        n    Gives better performance on add and remove compared to
             ArrayList.
        n    Gives poorer performance on get and set methods compared to
             ArrayList.


OOP: Collections                                                           17
ArrayList, Example
             // [Source: java.sun.com]
             import java.util.*;

             public class Shuffle {
                 public static void main(String args[]) {
                     List l = new ArrayList();
                     for (int i = 0; i < args.length; i++)
                         l.add(args[i]);
                     Collections.shuffle(l, new Random());
                     System.out.println(l);
                 }
             }




OOP: Collections                                             18
LinkedList, Example
             import java.util.*;
             public class MyStack {
                 private LinkedList list = new LinkedList();
                 public void push(Object o){
                     list.addFirst(o);
                 }
                 public Object top(){
                     return list.getFirst();
                 }
                 public Object pop(){
                     return list.removeFirst();
                 }

                   public static void main(String args[]) {
                       Car myCar;
                       MyStack s = new MyStack();
                       s.push (new Car());
                       myCar = (Car)s.pop();
                   }
             }

OOP: Collections                                               19
The ListIterator Interface
            public interface ListIterator extends Iterator {
                boolean hasNext();
                Object next();

                   boolean hasPrevious();
                   Object previous();

                   int nextIndex();
                   int previousIndex();

                   void remove();           // Optional
                   void set(Object o);      // Optional
                   void add(Object o);      // Optional
            }




OOP: Collections                                               20
The Map Interface
  • A Map is an object that maps keys to values. Also called an
       associative array or a dictionary.

  • Methods for adding and deleting
        n    put(Object key, Object value)
        n    remove (Object key)
  • Methods for extraction objects
        n    get (Object key)
  • Methods to retrieve the keys, the values, and (key, value) pairs
        n    keySet()   // returns a Set
        n    values()   // returns a Collection,
        n    entrySet() // returns a set

OOP: Collections                                                       21
The MAP Interface, cont.
      public interface Map {
                // Basic Operations
                Object put(Object key, Object value);
                Object get(Object key);
                 Object remove(Object key);
                boolean containsKey(Object key);
                boolean containsValue(Object value);
                 int size();
                boolean isEmpty();
                // Bulk Operations
                 void putAll(Map t);
                 void clear();
                // Collection Views
                 public Set keySet();
                public Collection values();
                 public Set entrySet();
                // Interface for entrySet elements
                 public interface Entry {
                     Object getKey();
                     Object getValue();
                     Object setValue(Object value);
                }
      }
OOP: Collections                                        22
HashMap and TreeMap Classes
  • The HashMap and HashTree classes implement the Map
       interface.

  • HashMap
        n    The implementation is based on a hash table.
        n    No ordering on (key, value) pairs.


  • TreeMap
        n    The implementation is based on red-black tree structure.
        n    (key, value) pairs are ordered on the key.




OOP: Collections                                                        23
HashMap, Example
 import java.util.*;

 public class Freq {
     private static final Integer ONE = new Integer(1);
     public static void main(String args[]) {
         Map m = new HashMap();

                   // Initialize frequency table from command line
                   for (int i=0; i < args.length; i++) {
                       Integer freq = (Integer) m.get(args[i]);
                       m.put(args[i], (freq==null ? ONE :
                                       new Integer(freq.intValue() + 1)));
                   }

                   System.out.println(m.size()+
                                   " distinct words detected:");
                   System.out.println(m);
          }
 }


OOP: Collections                                                             24
Static Methods on Collections
  • Collection
        n    Search and sort: binarySearch(), sort()
        n    Reorganization: reverse(), shuffle()
        n    Wrappings: unModifiableCollection,
             synchonizedCollection




OOP: Collections                                       25
Collection Advantages and Disadvantages
  Advantages                      Disadvantages
  • Can hold different types of   • Must cast to correct type
       objects.                   • Cannot do compile-time type
  •    Resizable                    checking.




OOP: Collections                                                  26
Summary
  • Array
        n    Holds objects of known type.
        n    Fixed size.


  • Collections
        n    Generalization of the array concept.
        n    Set of interfaces defined in Java for storing object.
        n    Multiple types of objects.
        n    Resizable.


  • Queue, Stack, Deque classes absent
        n    Use LinkedList.


OOP: Collections                                                     27

More Related Content

What's hot

Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Aijaz Ali Abro
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in javaCPD INDIA
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
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!
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEdureka!
 

What's hot (20)

Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
List in java
List in javaList in java
List in java
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
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...
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
 

Similar to Collections In Java

Similar to Collections In Java (20)

Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Lecture 24
Lecture 24Lecture 24
Lecture 24
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Collections
CollectionsCollections
Collections
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
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
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java 103
Java 103Java 103
Java 103
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Lists
ListsLists
Lists
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Collections
CollectionsCollections
Collections
 
Collections
CollectionsCollections
Collections
 

Recently uploaded

Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 

Recently uploaded (20)

Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 

Collections In Java

  • 1. Collections in Java • Arrays n Has special language support • Iterators n Iterator (i) • Collections (also called containers) n Collection (i) n Set (i), u HashSet (c), TreeSet (c) n List (i), u ArrayList (c), LinkedList (c) n Map (i), u HashMap (c), TreeMap (c) OOP: Collections 1
  • 2. Array • Most efficient way to hold references to objects. data Car Car Car Car index 0 1 2 3 4 5 6 7 • Advantages n An array know the type it holds, i.e., compile-time type checking. n An array know its size, i.e., ask for the length. n An array can hold primitive types directly. • Disadvantages n An array can only hold one type of objects (including primitives). n Arrays are fixed size. OOP: Collections 2
  • 3. Array, Example class Car{}; // minimal dummy class Car[] cars1; // null reference Car[] cars2 = new Car[10]; // null references for (int i = 0; i < cars2.length; i++) cars2[i] = new Car(); // Aggregated initialization Car[] cars3 = {new Car(), new Car(), new Car(), new Car()}; cars1 = {new Car(), new Car(), new Car()}; • Helper class java.util.Arrays n Search and sort: binarySearch(), sort() n Comparison: equals() (many overloaded) n Instantiation: fill() (many overloaded) n Conversion: asList() OOP: Collections 3
  • 4. Overview of Collection • A collection is a group of data manipulate as a single object. Corresponds to a bag. • Insulate client programs from the implementation. n array, linked list, hash table, balanced binary tree • Like C++'s Standard Template Library (STL) • Can grow as necessary. • Contain only Objects (reference types). • Heterogeneous. • Can be made thread safe (concurrent access). • Can be made not-modifiable. OOP: Collections 4
  • 5. Collection Interfaces • Collections are primarily defined through a set of interfaces. n Supported by a set of classes that implement the interfaces [Source: java.sun.com] • Interfaces are used of flexibility reasons n Programs that uses an interface is not tightened to a specific implementation of a collection. n It is easy to change or replace the underlying collection class with another (more efficient) class that implements the same interface. OOP: Collections 5
  • 6. Collection Interfaces and Classes OOP: Collections [Source: bruceeckel.com] 6
  • 7. The Iterator Interface • The idea: Select each element in a collection n Hide the underlying collection Collection Iterator list isEmpty() hasNext() add() next() remove() remove() ... • Iterators are fail-fast n Exception thrown if collection is modified externally, i.e., not via the iterator (multi-threading). OOP: Collections 7
  • 8. The Iterator Interface, cont. // the interface definition Interface Iterator { boolean hasNext(); Object next(); // note "one-way" traffic void remove(); } // an example public static void main (String[] args){ ArrayList cars = new ArrayList(); for (int i = 0; i < 12; i++) cars.add (new Car()); Iterator it = cats.iterator(); while (it.hasNext()) System.out.println ((Car)it.next()); } OOP: Collections 8
  • 9. The Collection Interface public interface Collection { // Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); // Optional boolean removeAll(Collection c); // Optional boolean retainAll(Collection c); // Optional void clear(); // Optional // Array Operations Object[] toArray(); Object[] toArray(Object a[]); } OOP: Collections 9
  • 10. The Set Interface • Corresponds to the mathematical definition of a set (no duplicates are allowed). • Compared to the Collection interface n Interface is identical. n Every constructor must create a collection without duplicates. n The operation add cannot add an element already in the set. n The method call set1.equals(set2) works at follows u set1 ⊆ set2, and set2 ⊆ set1 OOP: Collections 10
  • 11. Set Idioms • set1 ∪ set2 n set1.addAll(set2) • set1 ∩ set2 n set1.retainAll(set2) • set1 − set2 n set1.removeAll(set2) OOP: Collections 11
  • 12. HashSet and TreeSet Classes • HashSet and TreeSet implement the interface Set. • HashSet n Implemented using a hash table. n No ordering of elements. n add, remove, and contains methods constant time complexity O(c). • TreeSet n Implemented using a tree structure. n Guarantees ordering of elements. n add, remove, and contains methods logarithmic time complexity O(log (n)), where n is the number of elements in the set. OOP: Collections 12
  • 13. HashSet, Example // [Source: java.sun.com] import java.util.*; public class FindDups { public static void main(String args[]){ Set s = new HashSet(); for (int i = 0; i < args.length; i++){ if (!s.add(args[i])) System.out.println("Duplicate detected: " + args[i]); } System.out.println(s.size() + " distinct words detected: " + s); } } OOP: Collections 13
  • 14. The List Interface • The List interface corresponds to an order group of elements. Duplicates are allowed. • Extensions compared to the Collection interface n Access to elements via indexes, like arrays u add (int, Object), get(int), remove(int), set(int, Object) (note set = replace bad name for the method) n Search for elements u indexOf(Object), lastIndexOf(Object) n Specialized Iterator, call ListIterator n Extraction of sublist u subList(int fromIndex, int toIndex) OOP: Collections 14
  • 15. The List Interface, cont. Further requirements compared to the Collection Interface • add(Object)adds at the end of the list. • remove(Object)removes at the start of the list. • list1.equals(list2)the ordering of the elements is taken into consideration. • Extra requirements to the method hashCode. n list1.equals(list2) implies that list1.hashCode()==list2.hashCode() OOP: Collections 15
  • 16. The List Interface, cont. public interface List extends Collection { // Positional Access Object get(int index); Object set(int index, Object element); // Optional void add(int index, Object element); // Optional Object remove(int index); // Optional abstract boolean addAll(int index, Collection c); // Optional // Search int indexOf(Object o); int lastIndexOf(Object o); // Iteration ListIterator listIterator(); ListIterator listIterator(int index); // Range-view List subList(int from, int to); } OOP: Collections 16
  • 17. ArrayList and LinkedList Classes • The classes ArrayList and LinkedList implement the List interface. • ArrayList is an array based implementation where elements can be accessed directly via the get and set methods. n Default choice for simple sequence. • LinkedList is based on a double linked list n Gives better performance on add and remove compared to ArrayList. n Gives poorer performance on get and set methods compared to ArrayList. OOP: Collections 17
  • 18. ArrayList, Example // [Source: java.sun.com] import java.util.*; public class Shuffle { public static void main(String args[]) { List l = new ArrayList(); for (int i = 0; i < args.length; i++) l.add(args[i]); Collections.shuffle(l, new Random()); System.out.println(l); } } OOP: Collections 18
  • 19. LinkedList, Example import java.util.*; public class MyStack { private LinkedList list = new LinkedList(); public void push(Object o){ list.addFirst(o); } public Object top(){ return list.getFirst(); } public Object pop(){ return list.removeFirst(); } public static void main(String args[]) { Car myCar; MyStack s = new MyStack(); s.push (new Car()); myCar = (Car)s.pop(); } } OOP: Collections 19
  • 20. The ListIterator Interface public interface ListIterator extends Iterator { boolean hasNext(); Object next(); boolean hasPrevious(); Object previous(); int nextIndex(); int previousIndex(); void remove(); // Optional void set(Object o); // Optional void add(Object o); // Optional } OOP: Collections 20
  • 21. The Map Interface • A Map is an object that maps keys to values. Also called an associative array or a dictionary. • Methods for adding and deleting n put(Object key, Object value) n remove (Object key) • Methods for extraction objects n get (Object key) • Methods to retrieve the keys, the values, and (key, value) pairs n keySet() // returns a Set n values() // returns a Collection, n entrySet() // returns a set OOP: Collections 21
  • 22. The MAP Interface, cont. public interface Map { // Basic Operations Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk Operations void putAll(Map t); void clear(); // Collection Views public Set keySet(); public Collection values(); public Set entrySet(); // Interface for entrySet elements public interface Entry { Object getKey(); Object getValue(); Object setValue(Object value); } } OOP: Collections 22
  • 23. HashMap and TreeMap Classes • The HashMap and HashTree classes implement the Map interface. • HashMap n The implementation is based on a hash table. n No ordering on (key, value) pairs. • TreeMap n The implementation is based on red-black tree structure. n (key, value) pairs are ordered on the key. OOP: Collections 23
  • 24. HashMap, Example import java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); // Initialize frequency table from command line for (int i=0; i < args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq==null ? ONE : new Integer(freq.intValue() + 1))); } System.out.println(m.size()+ " distinct words detected:"); System.out.println(m); } } OOP: Collections 24
  • 25. Static Methods on Collections • Collection n Search and sort: binarySearch(), sort() n Reorganization: reverse(), shuffle() n Wrappings: unModifiableCollection, synchonizedCollection OOP: Collections 25
  • 26. Collection Advantages and Disadvantages Advantages Disadvantages • Can hold different types of • Must cast to correct type objects. • Cannot do compile-time type • Resizable checking. OOP: Collections 26
  • 27. Summary • Array n Holds objects of known type. n Fixed size. • Collections n Generalization of the array concept. n Set of interfaces defined in Java for storing object. n Multiple types of objects. n Resizable. • Queue, Stack, Deque classes absent n Use LinkedList. OOP: Collections 27