Collections

Goals for Today

Collections

Fibonacci Recursion Trace

Collection Interface

The Value of Interfaces

Why would we ever do this…

Queue<String> queue = new LinkedList<>();

// now work with queue to solve a problem.

Instead of this…

LinkedList<String> queue = new LinkedList<>();

// now work with the queue to solve a problem.

given that we have strictly less functionality to work with in the first example?

Socrative: Using Collections Effectively

Let’s say we want a method that returns an ArrayList with all duplicate elements removed. This seems reasonable:

 public static ArrayList<String> noDuplicates(ArrayList<String> items) {
    
    ArrayList<String> result = new ArrayList<String>();
    
    for (String item : items) {
      
      if (!result.contains(item)) {
        result.add(item);
      }
      
    }
    return result;
  }

Is this Correct?

How long would you expect it to run if items contains 1000000 distinct items?

A. Yes, around .01s

B. Yes, around 1s

C. Yes, more than a minute.

D. No, around .01 s

E. No, around 1s

F. No, more than a minute.

A better implementations…

public static ArrayList<String> noDuplicates(ArrayList<String> items) {
  return new ArrayList<String>(new HashSet<String>(items));
}

Or, if you prefer:

public static ArrayList<String> noDuplicates(ArrayList<String> items) {
  HashSet<String> setVersion = new HashSet<>(items);
  ArrayList<String> noDups = new ArrayList<>(setVersion);
  return noDups;
}

Warning: order of the items will not be retained unless you use a LinkedHashSet.

Iterable/Iterator

Collection extends Iterable…

Socrative Quiz

Fill in the blanks

The Set class implements the          interface which includes the          method.

When that method is called, it returns an object that implements the          interface.

That object provides the          method.

A. Iterator

B. next

C. Iterable

D. iterator

DON’T USE ITERATORS DIRECTLY!

Maps

Fibonacci Recursion Trace

HashMap Demo

import java.util.HashMap;
import java.util.Scanner;


public class HashMapDemo {

  public static void main(String args[]) {
    HashMap<String, String> eDirectory;
    Scanner kb = new Scanner(System.in);
    String key;

    eDirectory = new HashMap<String, String>();

    eDirectory.put("bernstdh", "David Bernstein");
    eDirectory.put("molloykp", "Kevin Molloy");
    eDirectory.put("spragunr", "Nathan Sprague");

    System.out.print("Enter an eid: ");
    key = kb.nextLine();
    System.out.println(eDirectory.get(key));

  }

}