3/11/18
Object Oriented Programming
         Java Collection Framework
                 Object Oriented Programming (OOP)
                         Year 2 – Semester 1
                                                                                           1
                                                               SLIIT - Faculty of Computing
Object Oriented Programming
     Collections in Java
     The Collections Framework is a sophisticated hierarchy of
     interfaces and classes that provide state-of-art technology for
     managing groups of objects.
                                                    Java Reference Book 09: Page 497
     The primary advantages of a collections framework are;
          q Reduces programming effort
          q Increases performance
          q Provides interoperability between unrelated APIs
          q Reduces the effort required to learn APIs
          q Reduces the effort required to design and implement APIs
          q Fosters software reuse
     Generics make Collections type safe. Before generics, collections
     stored Object references; can store any type of object. Thus avoids
     run-time mismatch errors.                           SLIIT - Faculty of Computing
Object Oriented Programming
      Hierarchy of Collections Framework
                                                                 The java.util package
                                                                 contains all the classes
                                                                 and interfaces for
                                                                 Collection framework
                                                               SLIIT - Faculty of Computing
                                                                                                    1
                                                                                                                 3/11/18
Object Oriented Programming
       Collection Interface
      • Collection is the foundation upon which the Collection
        Framework is built on.
      • Declaration:
            • Interface Collection <E>
            • E: specifies the type of objects that collection will hold
      • Methods of Collection interface;
                                                                                  SLIIT - Faculty of Computing
Object Oriented Programming
                Method                                                Description
public boolean add(Object element)         is used to insert an element in this collection.
public boolean addAll(Collection c)   is used to insert the specified collection elements in the invoking
                                      collection.
public boolean remove(Object element) is used to delete an element from this collection.
public boolean removeAll(Collection c)     is used to delete all the elements of specified collection from the
                                           invoking collection.
public boolean retainAll(Collection c)     is used to delete all the elements of invoking collection except
                                           the specified collection.
public int size()                          return the total number of elements in the collection.
public void clear()                        removes the total no of element from the collection.
public boolean contains(Object element) is used to search an element.
public boolean containsAll(Collection c) is used to search the specified collection in this collection.
public Iterator iterator()                 returns an iterator.
public Object[] toArray()                  converts collection into array.
public boolean isEmpty()                   checks if collection is empty.
public boolean equals(Object element)      matches two collection.
                                                                                                    5
public int hashCode()                      returns the hashcode number for collection.
                                                                              SLIIT - Faculty of Computing
Object Oriented Programming
       List Interface
      q Java.util.List is a child interface of Collection.
      q List is an ordered collection of objects in which duplicate values can be
        stored. Since List preserves the insertion order it allows positional
        access and insertion of elements.
      q List Interface is implemented by ArrayList, LinkedList, Vector and Stack
        classes.
      Queue Interface
       q The java.util.Queue is a subtype of java.util.Collection interface.
       q It is an ordered list of objects with its use limited to inserting elements
         at the end of list and deleting elements from the start of list. It follows
         First In First Out (FIFO) principle.
                                                                                                          6
                                                                                  SLIIT - Faculty of Computing
                                                                                                                      2
                                                                                                 3/11/18
Object Oriented Programming
       Set Interface
      q The java.util.Set interface is a subtype of Collection interface.
      q A Set is a Collection that cannot contain duplicate elements. It models
        the mathematical set abstraction.
      q Set interface is implemented by SortedSet interface and Hashset and
        LinkedHashSet classes.
      q SortedSet interface declares the behavior of a set sorted in ascending
        order. TreeSet class implements this interface.
                                                                  SLIIT - Faculty of Computing
Object Oriented Programming
      ArrayList Class
    q ArrayList class extends the AbstractList class and implements
      the List interface.
    q ArrayList support dynamic arrays (can increase and decrease
      size dynamically).
    q ArrayList constructors;
        § ArrayList() – Creates an empty array list.
        § ArrayList (Collection <? Extends > c) - Creates an array list that is
          initializd with the elements of the collection of c.
        § ArrayList (int capacity) – Creates an array list with initial capacity. The
          capacity is the underlying array that is used to store the elements. The
          capacity grows as elements are added to the array list.
                                                                  SLIIT - Faculty of Computing
Object Oriented Programming
      Example : ArrayList
                                           Ref: Java Complete Reference Pg: 512
                                                                ArrayListDemo.java
                                                                  SLIIT - Faculty of Computing
                                                                                                      3
                                                                                                                      3/11/18
Object Oriented Programming
      Obtaining Array from an ArrayList
       Reasons for converting array to an ArrayList
                  q To obtain faster processing time for certain operations
                  q To pass an array to a method that is not overloaded to
                    accept a collection
                  q To integrated collection-based code with legacy code
                    that don’t understand collections
                                                                                                           10
                                                                                       SLIIT - Faculty of Computing
Object Oriented Programming
      Example : ArrayList to Array
                                                                  Ref: Java Complete Reference Pg: 514
         import java.util.*;
         class ArrayListToArray {
            public static void main(String args[]) { // Create an array list.
             ArrayList<Integer> al = new ArrayList<Integer>();
                  // Add elements to the array list.
                   al.add(1);
                   al.add(2);
                   al.add(3);
                   al.add(4);
                  System.out.println("Contents of al: " + al);
                  // Get the array.
                  Integer ia[] = new Integer[al.size()];
                   ia = al.toArray(ia);
                  int sum = 0;
                                                                                      ArrayListToArray.java
                  // Sum the array.
                    for(int i =0 ; i< ia.length ; i++)
                         sum += i;
                 System.out.println("Sum is: " + sum);
             }
                                                                                                           11
         }
                                                                                       SLIIT - Faculty of Computing
Object Oriented Programming
    Example : forEach Loop for Iterating Over Collections
         import java.util.ArrayList;
         public class ForEachExample {
                 public static void main(String[] args) {
                   ArrayList<String> items = new ArrayList<>();
                   items.add("A");
                   items.add("B");
                   items.add("C");
                   items.add("D");
                   items.add("E");
                                                                                    ForEachExample.java
                     for (String item : items) {
                       System.out.println(item);
                     }
                 }
         }                                                                                                 12
                                                                                       SLIIT - Faculty of Computing
                                                                                                                           4
                                                                                                              3/11/18
Object Oriented Programming
      HashSet Class
    q HashSet extends AbstractSet and implements the Set interface.
    q It creates a collection that uses a hash table for storage.
    q In hashing, the informational content of a key is used to determine a
      unique value, called its hash code. The hash code is then used as the index
      at which the data associated with the key is stored. The transformation of
      the key into its hash code is performed automatically
    q HashSet constructors;
              • HashSet( ) - Default hash set.
              • HashSet(Collection<? extends E> c) - Initializes the hash set by using the
                                                    elements of c
              • HashSet(int capacity) - Initializes the capacity of the hash set to capacity
              • HashSet(int capacity, float fillRatio) - Initializes both the capacity and the fill ratio
                (also called load capacity ) of the hash set. The fill ratio must be between 0.0 and
                1.0, and it determines how full the hash set can be before it is resized upward.13
                                                                               SLIIT - Faculty of Computing
Object Oriented Programming
      Example : HashSet
                                                     Ref: Java Complete Reference Pg: 517
      import java.util.HashSet;
      public class HashSetDemo {
         public static void main(String args[]) {
      // Create a hash set.
           HashSet<String> hs = new HashSet<String>();
              // Add elements to the hash set.
              hs.add("Beta");
              hs.add("Alpha");
              hs.add("Eta");
              hs.add("Gamma");                                              HashSetDemo.java
              hs.add("Epsilon");
              hs.add("Omega");
              System.out.println(hs);
          }
      }
                                                                                                    14
                                                                               SLIIT - Faculty of Computing
Object Oriented Programming
      Working with Maps
      q A map is an object that stores associations between keys and
        values, or key/value pairs. Given a key, you can find its value.
      q Both keys and values are objects. The keys must be unique, but
        the values may be duplicated.
      q Some maps can accept a null key and null values, others cannot.
      q Map is useful if you have to search, update or delete elements
        on the basis of key
      q Maps are not part of the Collections Framework
                                                                                                    15
                                                                               SLIIT - Faculty of Computing
                                                                                                                   5
                                                                                                                      3/11/18
Object Oriented Programming
      The Map Classes
        Several classes provide implementations of the map interfaces. The
        classes that can be used for maps are summarized here:
                                                                    Ref: Java Complete Reference Pg: 537
                                                                                                           16
                                                                                       SLIIT - Faculty of Computing
Object Oriented Programming
      HashMap Class
     q The HashMap class extends AbstractMap and implements the Map
       interface. It uses a hash table to store the map.
     q HashMap is a generic class that has this declaration:
                      class HashMap<K, V>
                     K specifies the type of keys, and V specifies the type of values.
     q HashMap constructors
               §    HashMap( ) - Default hash map
               §    HashMap(Map<? extends K, ? extends V> m) - Initializes the hash map by
                    using the elements of m
               §    HashMap(int capacity) - Third form initializes the capacity of the hash map to
                    capacity. The default capacity is 16
               §    HashMap(int capacity, float fillRatio) - Initializes both the capacity and fill
                    ratio of the hash map by using its arguments. The meaning of capacity and fill
                                                                                                    17
                    ratio is the same as for HashSet. The default fill ratio is 0.75
                                                                                       SLIIT - Faculty of Computing
Object Oriented Programming
       Example : HashMap
                                                               Ref: Java Complete Reference Pg: 537
     public class HashMapDemo {
       public static void main(String args[]) {
         // Create a hash map.
         HashMap<String, Double> hm = new HashMap<String, Double>();
            // Put elements to the map
            hm.put("John Doe", new Double(3434.34));
            hm.put("Tom Smith", new Double(123.22));
            hm.put("Jane Baker", new Double(1378.00));
            hm.put("Tod Hall", new Double(99.22));
            hm.put("Ralph Smith", new Double(-19.08));
            // Get a set of the entries.
            Set<Map.Entry<String, Double>> set = hm.entrySet();
            // Display the set.
            for (Map.Entry<String, Double> me : set) {                              HashMapDemo.java
               System.out.print(me.getKey() + ": ");
               System.out.println(me.getValue());
            }
            // Deposit 1000 into John Doe's account.
            double balance = hm.get("John Doe");
            hm.put("John Doe", balance + 1000);
                                                                                                           18
            System.out.println("John Doe's new balance: " + hm.get("John Doe"));
       }}                                                                              SLIIT - Faculty of Computing
                                                                                                                           6
                                                                                       3/11/18
Object Oriented Programming
      Reference
      q Java Complete Reference – 9th Edition
      q Java T- Point:
                https://www.javatpoint.com/collections-in-java
      q Java Collections Tutorial - Jakob Jenkov
                http://tutorials.jenkov.com/java-collections/index.html
                                                                            19
                                                        SLIIT - Faculty of Computing