Why might we declare a variable as type “Collection”?
Why would we ever do this…
Instead of this…
given that we have strictly less functionality to work with in the first example?
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.
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
.
Collection extends Iterable…
Iterators are the magic behind for-each loops:
Is (pretty much) just shorthand for:
This would also work, but is terrible:
One more option, using a lambda function:
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
iterator
method.This doesn’t work:
This does:
Map
“maps” from Keys to Values, which may or may not be of the same type.Collection
or Iterable
.HashMap
- More efficient (on average).TreeMap
- Orders items according to the keys.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("duanzx", "Zhuojun Duan");
eDirectory.put("spragunr", "Nathan Sprague");
System.out.print("Enter an eid: ");
key = kb.nextLine();
System.out.println(eDirectory.get(key));
}
}