You are keeping a running tally of how many times each hashtag appears in a feed. Which collection fits best?
HashMap<String, Integer>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.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.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"));23The twoTag("java")values are different objects, but a record’sequalscompares by content, so the set treats them as one element and keeps only the first.1Tag("cse")is a different tag, so it stays in the set. Only the duplicatejavacollapses.0Eachaddof a new element does go in; aHashSetisn’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());
}
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();10feed.get(0)andpname the very same object — the list stored a reference, not a copy — so liking one shows up on the other.2Adding aPostto anArrayList<Post>doesn’t copy it, so there’s only ever one object here, not two to disagree.- It doesn’t compileThis compiles fine:
feed.get(0)returns aPost, so you can calllike()on it directly.
Given
ArrayList<Point> pts = new ArrayList<Point>(); where Point is record Point(int x, int y) { }, which line does not compile?pts.add("origin");pts.add(new Point(1, 2));APointis exactly what anArrayList<Point>accepts.int px = pts.get(0).x();getreturns aPoint, so the compiler lets you callx()on the result right away.int n = pts.size();size()returns anintno matter what the element type is.