☰ Contents Collections and Generics

Collections and Generics in Summary

You are keeping a running tally of how many times each hashtag appears in a feed. Which collection fits best?
  1. HashMap<String, Integer>
  2. ArrayList<String>
    A list would store every single use, and you’d still have to count them by hand afterwards. The map keeps the running count right under each tag.
  3. HashSet<String>
    A set answers only whether a tag has appeared, never how many times — it throws the repeats away, which is exactly the number you’re trying to keep.
  4. ArrayList<Integer>
    This loses which tag each count belongs to. The whole point is to look a count up by its tag.

What is tags.size() after this runs?

record Tag(String name) { }

HashSet<Tag> tags = new HashSet<Tag>();
tags.add(new Tag("java"));
tags.add(new Tag("java"));
tags.add(new Tag("cse"));
  1. 2
  2. 3
    The two Tag("java") values are different objects, but a record’s equals compares by content, so the set treats them as one element and keeps only the first.
  3. 1
    Tag("cse") is a different tag, so it stays in the set. Only the duplicate java collapses.
  4. 0
    Each add of a new element does go in; a HashSet isn’t empty just because it drops duplicates.
Finish the loop so counts maps each color to how many times it appears, then read back the count for "red".
import java.util.HashMap;

String[] votes = {"red", "blue", "red", "red", "green"};
HashMap<String, Integer> counts = new HashMap<String, Integer>();
void main() {
for (String v : votes) {
counts.put(v, );
}
int red = ;
System.out.println(red);
System.out.println(counts.size());
}

Using this chapter’s Post (with an int likes field and a like() method), what is p.likes after this runs?

ArrayList<Post> feed = new ArrayList<Post>();
Post p = new Post("ada", "hi");
feed.add(p);
feed.get(0).like();
  1. 1
  2. 0
    feed.get(0) and p name the very same object — the list stored a reference, not a copy — so liking one shows up on the other.
  3. 2
    Adding a Post to an ArrayList<Post> doesn’t copy it, so there’s only ever one object here, not two to disagree.
  4. It doesn’t compile
    This compiles fine: feed.get(0) returns a Post, so you can call like() on it directly.
Given ArrayList<Point> pts = new ArrayList<Point>(); where Point is record Point(int x, int y) { }, which line does not compile?
  1. pts.add("origin");
  2. pts.add(new Point(1, 2));
    A Point is exactly what an ArrayList<Point> accepts.
  3. int px = pts.get(0).x();
    get returns a Point, so the compiler lets you call x() on the result right away.
  4. int n = pts.size();
    size() returns an int no matter what the element type is.