HashMaps and Collections in Java

Learn to store and find data by key with HashMap, count and group values, and keep unique values with HashSet. See what the List, Set and Map interfaces promise, sort lists and give your own classes a natural order with Comparable, and choose the collection that fits each task.

BeginnerLesson 7 of 11 in Object-Oriented Programming with Java Course

What you will learn

  1. Create hash maps, add, read, update and remove key–value pairs, loop over a map's contents, and use your own classes as keys that the map can find again.
    • Create a HashMap and put, get, update and remove entries
      Declare a HashMap with its key and value types, store pairs with put, read them with get, and handle keys that are missing.
    • Loop over keys, values and entries
      Go through every pair in a map with keySet, values and entrySet, know what order to expect, and change a map safely while looping.
    • Use your own objects as map keys
      Make objects of your own classes work as keys by overriding equals and hashCode together, and keep keys unchanged while they are in a map.
  2. Use maps to count how often things occur, collect related values under one key, and build lookup tables that find objects quickly.
    • Count occurrences and add up totals per key
      Build frequency tables and running totals with the getOrDefault pattern, and read the results correctly.
    • Group values under one key with lists and sets as values
      Build maps whose values are lists or sets, add items to the right group, and avoid the errors that lose or break groups.
    • Look up objects and prices quickly with a map index
      Use maps as lookup tables and indexes that find objects by a unique key, keep them inside a class, and keep several indexes consistent.
  3. Use HashSet to store values without duplicates, test membership quickly, and combine sets with union, intersection and difference.
    • Store unique values and test membership with HashSet
      Add, check and remove values in a HashSet, use the result of add, and remove duplicates from a list.
    • Combine sets and keep them in order
      Compute unions, intersections and differences without damaging the original sets, compare sets, and pick an ordered set when order matters.
  4. Declare collections by their interface types, know what each interface promises, and use the shared methods that work across implementations.
    • Declare variables and parameters with interface types
      Explain what an interface type is, declare collections as List, Set or Map, and write methods that accept any implementation.
    • Know what List, Set and Map guarantee
      Compare the promises of the three interfaces, recognize their main implementations, and work with unmodifiable collections made with of.
  5. Sort lists in natural order, give your own classes a natural order by implementing Comparable, and use that order in sorted sets and maps.
    • Sort lists of numbers and strings
      Sort a list in place with Collections.sort, predict the order of strings, and sort in reverse or ignoring case.
    • Implement Comparable in your own class
      Give a class a natural order by implementing Comparable and writing compareTo with safe comparisons of numbers and strings.
    • Break ties and use sorted sets and maps
      Order objects by several fields, keep compareTo consistent with equals, and use TreeSet and TreeMap to keep data sorted.
  6. Compare how fast common operations are in each collection and pick the type that fits what the program has to do with its data.
    • Compare the cost of common collection operations
      Estimate how the time of lookups, inserts and removals grows with the size of each collection, and spot slow patterns.
    • Pick a collection that fits the task
      Answer a few questions about order, duplicates and lookup to choose between arrays, lists, sets and maps, and combine them for more complex data.

HashMaps and Collections in Java study guide

6 chapters

1

Store and look up data by key with HashMap

A product code can lead straight to a stock quantity, without searching a list. Maps make that link explicit, but using them well also means handling missing keys, visiting pairs safely, and defining when two key objects count as equal. Start with a small stock map, then follow how its contents change and how Java finds a stored key again. The same equality rules will matter when you use sets.

1.1 Create a HashMap and put, get, update and remove entries

A map stores a link from each key to one value. In a stock map, a product name is the key and its quantity is the value. Two products can have the same quantity, but one product key cannot hold two separate entries.

Create the map
import java.util.HashMap;

HashMap<String, Integer> stock = new HashMap<>();

The first type, String, describes keys. The second, Integer, describes values. The diamond <> on the right lets Java infer those types. Type arguments must be reference types: use Integer, Double, Character, or Boolean instead of int, double, char, or boolean. Java boxes a plain int when it stores it as an Integer, and unboxes an Integer when an int is needed.

Follow each change
stock.put("apple", 12);
stock.put("pear", 7);
Integer previous = stock.put("apple", 15);

The first call creates apple=12; the second adds pear=7. The third finds the existing "apple" key and replaces its value. The map now has two entries, and previous holds 12. A put for a key with no previous mapping returns null.

stock.get("apple") now returns 15. stock.remove("pear") returns 7 and removes that entry. Removing "pear" again returns null. size() counts entries, isEmpty() tests whether there are none, and clear() removes every entry.

Handle a missing key

stock.get("kiwi") returns null, and stock.containsKey("kiwi") returns false. This statement compiles but fails when it runs:

int quantity = stock.get("kiwi");

Java tries to unbox null into an int, causing a NullPointerException. For a map of non-null quantities, use a default:

int quantity = stock.getOrDefault("kiwi", 0);

This gives 0 without adding "kiwi" to the map. You can also check containsKey before reading. containsValue(15) asks whether any entry has that value; it may scan all values, so it is different from finding a known key.

A HashMap also permits a null key and null values. If a key is explicitly mapped to null, getOrDefault returns that stored null, not the default. containsKey distinguishes that case from a missing key. Quantity maps are simpler when every stored quantity is a real number.

Match keys and values correctly

String keys are case-sensitive: "apple", "Apple", and "apple " are different. Apply the same cleanup before storing and searching, such as name.trim().toLowerCase(). Cleaning only a search key cannot fix inconsistent stored keys.

Compare boxed values by content with equals. If two entries each hold 1000, their Integer references can differ, so == can be false even though their numeric contents match. After checking that both values are non-null, a.equals(b) compares their contents.

Key Takeaways

  • Each unique key maps to one value; values may repeat.
  • put replaces an existing value and returns the previous value.
  • A missing get returns null; unboxing it causes a NullPointerException.
  • getOrDefault supplies a default only for an absent key.
  • Match string keys consistently and compare boxed values by content.

1.2 Loop over keys, values and entries

A map can answer a single lookup or supply all its data to a loop. Choose the view that gives the pieces the loop needs. The views are connected to the map, so changes through them can change the map too.

Choose keys, values, or entries

Use keySet() to visit keys. A lookup inside that loop can recover each value:

for (String name : phoneBook.keySet()) {
    System.out.println(name + ": " + phoneBook.get(name));
}

Use values() when keys are irrelevant. For stock quantities apple 15, pear 7, and fig 3:

int total = 0;
for (int quantity : stock.values()) {
    total += quantity;
}

The total becomes 25. Repeated values are still separate contributions: a values view is not a set.

An entry holds a key and its value together. Import java.util.Map and use Map.Entry<K, V> with getKey() and getValue(). This avoids a second lookup:

String best = null;
int bestScore = Integer.MIN_VALUE;
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    if (best == null || entry.getValue() > bestScore) {
        best = entry.getKey();
        bestScore = entry.getValue();
    }
}

For Ana 82, Ben 91, and Cai 77, the result is Ben with 91. The best == null test also handles a first score equal to the smallest possible int. An empty map leaves best as null.

Make order an explicit choice

A HashMap promises no iteration order. Insertion order, sorted order, or today's printed order cannot be assumed. A LinkedHashMap preserves insertion order; a TreeMap visits sorted keys. If two scores tie, the loop above keeps the first one visited. With a HashMap, either tied name could win. Add an explicit tie rule when the result must be predictable.

Remove entries through the iterator

Calling stock.remove(key) inside a for-each loop over stock.keySet() changes the keys behind the loop. It can cause a ConcurrentModificationException. Detection is best effort; an exception-free run does not make that pattern valid.

Use the iterator's own removal method:

Iterator<Map.Entry<String, Integer>> it =
    stock.entrySet().iterator();
while (it.hasNext()) {
    if (it.next().getValue() == 0) {
        it.remove();
    }
}

Import java.util.Iterator. For apple 15, pear 0, fig 0, and kiwi 4, this removes pear and fig. Another safe approach records keys in a list, finishes the loop, then removes those keys.

Replacing an existing value does not add or remove a key. During an entry loop, entry.setValue(entry.getValue() * 2) can double the quantities safely. Do not add new keys through the map during that loop.

Separate a view from a copy

stock.keySet().remove("apple") removes the corresponding map entry. A separate list made with new ArrayList<>(stock.keySet()) is a copy of the current keys. Sorting that list does not reorder the map, and removing a name from the list does not remove its mapping.

Key Takeaways

  • Use keySet, values, or entrySet according to what the loop needs.
  • HashMap has no guaranteed iteration order; resolve ties explicitly.
  • Use an iterator’s remove to delete during traversal.
  • Replacing an existing value is allowed during traversal.
  • Map views are linked; a copied key list is separate.

1.3 Use your own objects as map keys

A product ID stored as a String already has useful equality rules. A key made from your own class needs a decision: do two separate objects with the same data represent the same key?

Hash codes narrow the search; equality confirms it

A HashMap uses hashCode() to help locate a key and equals() to check a match. Equal keys must have equal hash codes. Different keys can share a hash code; equality still tells them apart. Standard value classes such as String and Integer already follow this contract.

Without overrides, a class inherits identity-based equality from Object. Two separately created points with coordinates 2 and 3 are different keys even though their fields match:

labels.put(new Point(2, 3), "door");
String label = labels.get(new Point(2, 3));

With identity equality, label is null. The lookup created a second object, not the object used for insertion.

Override the pair together

Here a point's coordinates define its content:

import java.util.Objects;

final class Point {
    private final int x;
    private final int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (!(other instanceof Point)) {
            return false;
        }
        Point point = (Point) other;
        return x == point.x && y == point.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}

The identity check handles the same object quickly. The type check rejects null and unrelated objects. The final comparison checks both coordinates. Objects.hash(x, y) builds the hash code from those same fields. With this class, the lookup above returns "door".

Overriding only equals leaves inherited hashing that does not promise equal hash codes for separate objects with equal fields. A map can then miss an equal key. A constant hash code would preserve correctness, but make searching slow. Generating both overrides in an editor helps avoid mismatched fields.

Use the exact method signature

public boolean equals(Point other) overloads the method; it does not replace equals(Object). Map lookup uses equals(Object), so the new overload does not give the map content equality. The @Override annotation makes a wrong signature a compiler error instead of a hidden lookup bug.

Keep key identity stable

Do not change fields that determine a key's equality or hash code while it is stored. If a stored point changes from (2, 3) to (5, 3), the map may no longer find it under either value even though size() is unchanged. Remove it before changing it, then insert it again. Making key fields final, as above, prevents this mistake.

These rules also determine membership in a HashSet. An ArrayList uses equals for content searches such as contains; it does not need hash codes for that search.

Key Takeaways

  • Equal objects must have equal hash codes; unequal objects may share one.
  • Override equals(Object) and hashCode() with matching fields.
  • @Override catches a mistaken equals overload.
  • Keep equality and hash-code fields unchanged while a key is stored.
2

Count, group and index data with maps

A map can build useful information as a program reads data: a count for each word, a list for each course, or an object for each ID. The important choice is what one value represents. A number accumulates a result; a list or set collects a group; an object reference gives an index. Trace each update from an empty map so that first occurrences, repeated keys, and shared objects all have clear behavior.

2.1 Count occurrences and add up totals per key

A frequency table has one key for each distinct item and a number showing how often it occurs. The first occurrence starts a count; every later occurrence updates that same entry.

Build a count one item at a time
HashMap<String, Integer> counts = new HashMap<>();
for (String word : text.split(" ")) {
    int oldCount = counts.getOrDefault(word, 0);
    counts.put(word, oldCount + 1);
}

For the text "the cat saw the dog and the cat ran", the first "the" is missing, so its old count is 0 and its new count is 1. Its next two appearances change that entry to 2 and then 3. "cat" finishes at 2; "saw", "dog", "and", and "ran" finish at 1 each.

There are 6 distinct words, so counts.size() is 6. The values add to 9, the number of word occurrences. These measure different things: the map's size is not the length of the original sequence.

The update can be written on one line:

counts.put(word, counts.getOrDefault(word, 0) + 1);

A longer equivalent checks containsKey, increments an existing count, and stores 1 for a new key. All stored counts in this pattern are non-null.

Preserve the old result

Calling counts.put(word, 1) for every word repeatedly overwrites each count with 1. It records that a word exists but loses its frequency. Calling counts.get(word) + 1 without handling the first occurrence tries to unbox null and fails. The default belongs in the read step; the increased count must then be stored back.

Decide what counts as the same item

String equality is exact. "The" and "the" are different keys, as are "cat" and "cat,". If the task treats those as the same word, clean each token before counting it. Lowercase text and remove the punctuation the program treats as separators. Use one consistent rule so that results do not depend on which spelling appeared first.

The key can also be a character. With HashMap<Character, Integer>, a loop over "banana".toCharArray() produces a=3, n=2, and b=1 using the same read-increase-store pattern.

Accumulate amounts instead of occurrences

For category totals, add the current amount instead of 1:

HashMap<String, Double> totals = new HashMap<>();
double oldTotal = totals.getOrDefault(category, 0.0);
totals.put(category, oldTotal + amount);

Food 12.50, transport 3.20, and food 7.25 give food 19.75 and transport 3.20. The default is 0.0, matching the Double value type. The map still has one entry per category, however many amounts contributed.

Read the completed table

Loop over entries to find the largest count or total, remembering the best key and value. Specify a tie rule if needed. For an alphabetical report, new TreeMap<>(counts) copies the mappings into sorted key order. The count values stay unchanged; sorting the keys does not sort categories by their totals.

Key Takeaways

  • A frequency map stores one count per distinct key.
  • Read the old count with a zero default, add one, and store the result.
  • Map size counts distinct items; the sum of counts measures occurrences.
  • Normalize text consistently before counting.
  • Use the same update pattern to add amounts per key.
  • Choose report order separately from the accumulated values.

2.2 Group values under one key with lists and sets as values

A map value can be a collection. When several students belong to one course, the course is a key and the associated list holds all its students. The map's unique-key rule still applies: the list is the one value for that course.

Create a group before adding to it
HashMap<Character, ArrayList<String>> groups = new HashMap<>();
for (String fruit : fruits) {
    char letter = fruit.charAt(0);
    if (!groups.containsKey(letter)) {
        groups.put(letter, new ArrayList<>());
    }
    groups.get(letter).add(fruit);
}

For "apple", "banana", "avocado", "cherry", and "blueberry", the first fruit creates the list for a and adds "apple". "Banana" creates the list for b. "Avocado" finds the existing a list and appends to it. The result is a → [apple, avocado], b → [banana, blueberry], and c → [cherry]. Each list keeps its own insertion order even though the HashMap does not order its keys.

The check can be shortened:

groups.putIfAbsent(letter, new ArrayList<>());
groups.get(letter).add(fruit);

putIfAbsent keeps an existing non-null list. The following get returns that list, ready for the addition.

Keep the list you have already built

An unconditional groups.put(letter, new ArrayList<>()) inside the loop replaces the old list on every occurrence. Only the last fruit for each letter survives after the next add. The opposite error is skipping creation entirely: groups.get(letter).add(fruit) throws a NullPointerException for a new key because no list exists yet.

Understand the reference

get returns the stored list reference. Adding to it changes that same list, so there is no need to put it back. This also explains a sharing bug:

ArrayList<String> shared = new ArrayList<>();
courses.put("Art", shared);
courses.put("Music", shared);
courses.get("Art").add("Jin");

Both keys now lead to [Jin]. Two keys did not create two lists. Make a fresh list for each new group when the groups should be independent.

Choose lists or sets within groups

A list preserves repeated additions. A set prevents duplicates within that group. A HashMap<String, HashSet<String>> can therefore collect each student's distinct course memberships without counting the same student twice in one course. The set rule applies inside each value; the outer map still has one entry per course.

For a read of a possibly missing group, check containsKey or use groups.getOrDefault(letter, new ArrayList<>()). An absent key then yields an empty list for that call. The default list is not automatically inserted; adding to it does not create a stored group.

Removing a group's last item leaves the key mapped to an empty collection. If the program should stop listing empty groups, check isEmpty() and remove that key too. Count groups with the outer map's size and items with the inner collections' sizes.

Key Takeaways

  • Ensure a group exists, then add to its stored list or set.
  • Create a fresh collection for each independent group.
  • get returns the stored reference, so inner changes need no extra put.
  • List values keep repetitions; set values keep distinct group members.
  • An empty stored group still has a map entry.

2.3 Look up objects and prices quickly with a map index

An index maps an identifying key to an object. A library can find a book by ISBN without scanning every book in a list. A lookup table uses the same shape to connect a code to a simple value, such as a product price.

Choose an identifying key

A HashMap<String, Book> can map an ISBN to its book. Each lookup needs only the key. A person's name is often a poor unique key: storing another person called "Sam Lee" under that same string replaces the previous person. Use a unique ID, or use a grouping map if one name is meant to lead to several people.

Keep an index inside the class responsible for the data:

class Library {
    private HashMap<String, Book> byIsbn;

    Library() {
        byIsbn = new HashMap<>();
    }

    void addBook(Book book) {
        byIsbn.put(book.getIsbn(), book);
    }

    Book findByIsbn(String isbn) {
        return byIsbn.get(isbn);
    }
}

Here Book supplies a getIsbn() method. Callers use addBook and findByIsbn; they do not need to know which map implementation is stored. The private field also gives the class one place to maintain its rules about adding and replacing books.

Check a missing result

If findByIsbn returns null, no book was found. Test the result before calling a method on it:

Book found = library.findByIsbn("978-0-00-000000-2");
if (found != null) {
    found.setOnLoan(true);
}

Calling setOnLoan directly on a missing result would throw a NullPointerException. A method such as hasBook(isbn) is another way to let callers test for a key.

Follow shared objects across indexes

A map stores an object reference, not a new copy of that object. If the same book is in an all-books list, an ISBN map, and an author grouping, setOnLoan(true) changes the one book that all three refer to. This avoids three separate book objects drifting apart.

The collection structures themselves still need maintenance. Removing a book from the ISBN map does not remove its reference from an author's list. If a library keeps both indexes, its add and remove methods must update both. Centralizing those changes in methods such as addBook and removeBook helps keep searches consistent.

Use a table in a calculation

Suppose a price table has coffee 2.50, tea 2.00, and muffin 3.25. For two coffees and one muffin:

double cost = 2 * prices.get("coffee") + prices.get("muffin");

The coffee subtotal is 5.00; adding 3.25 gives 8.25. The keys identify products, and the values supply the amounts. A missing product needs an explicit decision before calculation: a zero default would silently treat it as free. The same lookup technique can therefore need a different missing-key rule from a frequency table.

Key Takeaways

  • An index finds objects by an identifying key.
  • Use a unique key or group multiple matching objects explicitly.
  • Indexes share object references, but additions and removals must update each index.
  • Keep data maps private and expose methods that maintain their rules.
3

Keep unique values with sets

Sometimes the question is simply whether a value has appeared before. Sets fit that question directly and can also compare groups of values, such as people attending two events. Their lack of duplicate elements changes both the code you write and what the final size means. Work with membership first, then combine sets and choose whether their values should appear in insertion order or sorted order.

3.1 Store unique values and test membership with HashSet

A set holds each value at most once. It suits questions such as "Has this value appeared before?" or "How many different values occur?" A HashSet gives fast average membership checks without promising a display order.

Add and check values
import java.util.HashSet;

HashSet<String> visited = new HashSet<>();
boolean first = visited.add("Oslo");
boolean second = visited.add("Lima");
boolean third = visited.add("Oslo");
visited.add("Pune");

The three stored booleans are true, true, and false. The second "Oslo" matches an existing element, so it is not added. The set's size is 3. A duplicate addition does not replace a numbered slot because a set has no index.

visited.contains("Lima") returns true. visited.remove("Lima") removes it and returns true; repeating that removal returns false. Use a for-each loop to visit values. There is no get(0) for the first value of a HashSet.

Remove duplicates from a list
ArrayList<Integer> values = new ArrayList<>();
values.add(3);
values.add(1);
values.add(3);
values.add(2);
values.add(1);
HashSet<Integer> distinct = new HashSet<>(values);

The set has three values: {1, 2, 3}. Its actual iteration order is unspecified. The source list still has five elements because the constructor creates a separate collection.

Use new LinkedHashSet<>(values) to keep first-occurrence order, giving 3, 1, 2. Use new TreeSet<>(values) to obtain sorted values, 1, 2, 3. Sets are written with curly braces here to emphasize membership; Java's standard set toString() uses square brackets.

Detect the first repetition

The result of add can do the membership test and insertion together:

HashSet<Integer> seen = new HashSet<>();
for (int number : numbers) {
    if (!seen.add(number)) {
        System.out.println(number);
        break;
    }
}

For [4, 7, 2, 7, 4], the loop prints 7. It is the first value encountered for a second time, even though 4 appeared earlier in the sequence. Before 7 repeats, the set contains 4, 7, and 2. The failed insertion triggers the stop.

Know what a set cannot tell you

Checking contains before every add is unnecessary because add already handles duplicates. A list plus a contains check can also keep values unique, but each list search may scan all the stored elements. A HashSet expresses the rule directly.

Equality matters for your own objects. A HashSet<Point> needs content-based equals and a matching hashCode to merge separately created points with equal coordinates. Without those overrides, separate instances remain separate elements.

Finally, size() measures distinct values, not occurrences. The nine words in "the cat saw the dog and the cat ran" produce six distinct words. A set no longer tells you that "the" occurred three times; use a frequency map when those counts matter.

Key Takeaways

  • HashSet stores unique values with no index or guaranteed order.
  • add returns false when an equal value is already present.
  • A copied set removes duplicates without changing the source list.
  • Use the result of add to detect a repeated value.
  • Set size counts distinct values; frequencies need a map.

3.2 Combine sets and keep them in order

Sets can describe groups and compare their membership. If two event lists contain the same person several times, a set first reduces each list to the people who attended. Set operations then answer questions about either event, both events, or only one.

Combine two groups

Let Monday be {Ana, Ben, Cai, Dee} and Tuesday be {Ben, Dee, Eva}.

QuestionMethod on a copy of MondayResult
Who attended either day?addAll(tuesday){Ana, Ben, Cai, Dee, Eva}
Who attended both days?retainAll(tuesday){Ben, Dee}
Who attended Monday only?removeAll(tuesday){Ana, Cai}

These operations are union, intersection, and difference. They change the receiving set and return a boolean saying whether it changed. They do not return a new result set.

Preserve the original

Make a copy before changing membership if Monday is still needed:

HashSet<String> both = new HashSet<>(monday);
both.retainAll(tuesday);

both starts with all four Monday names. retainAll removes Ana and Cai because Tuesday lacks them. Monday itself remains unchanged. To find Tuesday only, start with a copy of Tuesday and remove Monday's names, giving {Eva}. Difference has a direction; reversing it changes the question.

Check subsets and equality

monday.containsAll(group) asks whether every value in group is present on Monday. For {Ben, Dee}, it returns true: that group is a subset of Monday. It does not require Monday to contain only those two people.

Two sets are equal when their elements match, regardless of insertion order or implementation. A HashSet containing "x" and "y" equals a TreeSet containing "y" and "x". Membership decides set equality, so order alone cannot make them unequal.

Choose an order for traversal
ImplementationOrder when visiting elements
HashSetNo guarantee
LinkedHashSetInsertion order
TreeSetSorted order

All three avoid duplicates. Use LinkedHashSet when the first time each name appeared matters. Use TreeSet when each traversal should already be sorted. For strings, natural sorting follows character codes: lowercase and uppercase forms do not behave like a single case-insensitive alphabet.

A TreeSet with its default constructor needs elements that have a natural comparison, such as strings, numbers, or objects implementing Comparable. In that set, a comparison result of zero marks a duplicate. A class that supplies no natural comparison causes a ClassCastException when inserted. Supplying an explicit comparator is another way to define a tree collection's order; the default examples use natural order.

Key Takeaways

  • addAll, retainAll, and removeAll mutate the receiving set.
  • Copy a set first when its original membership is still needed.
  • containsAll checks a subset; set equality ignores order.
  • Choose hash, linked, or tree implementations for unspecified, insertion, or sorted order.
4

Program with the List, Set and Map interfaces

The type on the left of a collection declaration tells the rest of the program what operations it can use. The class on the right supplies those operations and may promise a particular order. Learning to read both sides makes collection code easier to change and methods easier to reuse. It also helps explain why a list, a set, and a map behave differently even when they contain similar-looking data.

4.1 Declare variables and parameters with interface types

An interface describes operations that an implementing class provides. It lets a variable describe what code needs while leaving the storage choice to a concrete class. List, Set, and Map are collection-related interfaces in java.util.

Read the two sides of a declaration
List<String> names = new ArrayList<>();
Set<String> tags = new HashSet<>();
Map<String, Integer> counts = new HashMap<>();

The left side declares the variable's type. The right side creates an object of a class that implements it. Import both types, such as java.util.List and java.util.ArrayList. You cannot write new List<>() or new Map<>(): an interface is not a concrete object to construct.

Code using counts can call put, get, and entrySet because Map declares them. If alphabetical keys become useful, change the construction to new TreeMap<>(). Existing calls still compile. Their order can change because implementations may make different order promises; the interface does not make them identical in every behavior.

Accept the capability a method needs

A method that only counts long words can accept a Collection:

static int countLong(Collection<String> words, int min) {
    int count = 0;
    for (String word : words) {
        if (word.length() >= min) {
            count++;
        }
    }
    return count;
}

For ["a", "tree", "house"] and a minimum of 4, it returns 2. The same method can receive an ArrayList, a LinkedList, a HashSet, or List.of(...) because it only reads the elements. A set may have already removed duplicates, so it can supply different input data from a list.

Using an interface parameter avoids requiring one particular storage class when the method does not need it. If positions are necessary, accept List. If key lookup is necessary, accept Map.

Know the limits of the declared type
List<String> names = new ArrayList<>();
names.ensureCapacity(100);  // does not compile

The object is an ArrayList, but List does not declare ensureCapacity. The compiler checks the variable's declared type. Use a concrete class type when its special operation is actually needed; do not change ordinary list parameters merely to match one caller's class.

Place Map beside Collection

List and Set extend Collection, which describes a group of elements. It declares methods such as add, remove, contains, size, isEmpty, addAll, and clear. Whether a mutation is supported depends on the actual collection.

Map does not extend Collection. It stores associations and supplies views that are collections: keySet() is a Set, values() is a Collection, and entrySet() is a Set of entries. Pass counts.values() to a method needing a collection of values, not counts itself.

A class can implement several interfaces. LinkedList implements both List and Deque, a double-ended queue interface. Your own class names its promised interfaces after implements, as in class Member implements Comparable<Member>.

Key Takeaways

  • Declare the needed interface on the left and construct an implementing class on the right.
  • Interface parameters accept different implementations with the needed operations.
  • A variable exposes only methods declared by its type.
  • List and Set extend Collection; Map supplies collection views.

4.2 Know what List, Set and Map guarantee

Choose an interface by the rules your data needs. Similar-looking contents do not make a list, a set, and a map interchangeable: each gives different meaning to positions, repetition, and equality.

Compare the promises
InterfaceWhat it storesImportant rule
ListElements in positions starting at 0Repeated elements are allowed
SetDistinct elementsNo indexed get operation
MapKey–value pairsKeys are unique; values may repeat

ArrayList and LinkedList implement List. HashSet, LinkedHashSet, and TreeSet implement Set. HashMap, LinkedHashMap, and TreeMap implement Map. Hash versions promise no traversal order; linked versions preserve insertion order; tree versions maintain sorted elements or keys. Putting an existing key again in an ordinary insertion-ordered LinkedHashMap keeps that key's place.

Read integer-list removal carefully

A List<Integer> has two relevant overloads:

List<Integer> numbers = new ArrayList<>(List.of(1, 5, 7));
numbers.remove(1);

The argument 1 is an int, so Java removes index 1: the value 5. The result is [1, 7]. Starting again with [1, 5, 7], numbers.remove(Integer.valueOf(1)) selects removal by value and leaves [5, 7]. The wrapper object makes the intended overload clear.

Compare contents with the right rule

Two lists are equal when the same elements occur in the same order. An ArrayList [1, 2] equals a LinkedList [1, 2], but not a list [2, 1]. Two sets compare membership, ignoring order. Two maps compare mappings, so insertion order does not affect map equality. Their concrete classes can differ while their contents are equal under the interface's rule.

Recognize unmodifiable collections
List<String> labels = List.of("a", "b");
Set<Integer> levels = Set.of(1, 2, 3);
Map<String, Double> prices = Map.of("tea", 2.0, "coffee", 2.5);

These factories return unmodifiable collections. Attempts to add, remove, replace, or sort their contents throw UnsupportedOperationException. Map.of accepts up to ten key–value pairs.

All three reject null elements, keys, or values with NullPointerException. Set.of rejects duplicate elements and Map.of rejects duplicate keys with IllegalArgumentException. List.of allows duplicates because a list may repeat an element. The set and map factory results have unspecified iteration order.

Copy when changes are needed

new ArrayList<>(labels) creates a modifiable list with the same elements. new HashSet<>(someList) and new HashMap<>(someMap) likewise create separate collection structures.

These copies are shallow: they hold the same element references. Removing an element from a copy leaves the original structure intact, but changing a mutable object through either collection changes the shared object. An unmodifiable collection prevents edits to its structure; it does not freeze every object stored inside it.

Key Takeaways

  • Lists have positions and duplicates; sets have distinct elements; maps have unique keys.
  • remove(1) on an integer list removes an index; remove(Integer.valueOf(1)) removes a value.
  • List equality checks order; set and map equality check contents without insertion order.
  • of factories are unmodifiable and reject nulls.
  • Set.of rejects duplicate elements; Map.of rejects duplicate keys.
  • A modifiable copy separates collection structure but shares element references.
5

Sort collections with Comparable

Sorting puts values into an order that other code can use. Numbers and strings already know their natural order; objects of your own classes need an explicit rule. Follow a list through a sort, then write a comparison that handles numbers, text, and ties safely. The rule matters beyond lists: a sorted set or map also uses it to decide when two elements or keys occupy the same place.

5.1 Sort lists of numbers and strings

A list keeps an order, but that order may simply reflect how values arrived. Sorting rearranges the list using a comparison rule. Java already supplies natural ordering for numbers and strings.

Sort a modifiable list in place
List<Double> values = new ArrayList<>(List.of(3.5, -1.0, 2.25));
Collections.sort(values);

Import java.util.Collections. The same list now holds [-1.0, 2.25, 3.5]. The sort returns void, so values = Collections.sort(values) does not compile. values.sort(null) also sorts in natural order. For an array, use Arrays.sort(array); an array containing 5, 2, and 8 becomes 2, 5, 8.

Predict string order character by character

String comparison examines the first differing character. If one string is a prefix of another, the shorter comes first. Thus "apple" precedes "apples".

The list ["pear", "Banana", "apple", "10", "9"] sorts to ["10", "9", "Banana", "apple", "pear"]. For these characters, digits precede uppercase letters and uppercase precedes lowercase. "10" precedes "9" because '1' comes before '9'; string order does not interpret digit strings as whole numbers. Store numeric data as numbers when numeric order is needed.

Use ready-made alternative orders
names.sort(String.CASE_INSENSITIVE_ORDER);
values.sort(Collections.reverseOrder());

The first call orders ["pear", "Banana", "apple"] as ["apple", "Banana", "pear"] without changing the stored capitalization. The second uses descending natural order. Numbers 4, 9, and 1 become 9, 4, and 1. These arguments are comparators, objects that supply an alternative order.

Collections.reverse(list) only reverses the current sequence. It produces descending order if that sequence was already sorted ascending; it does not sort an arbitrary list by itself.

Keep ties stable

List sorting is stable: elements that compare as equal retain their previous relative order. If a score-only comparison ties two people, their earlier order in the list remains. Stability preserves that input order; it does not invent an alphabetical tie-breaker.

Recognize failures and shortcuts

A list from List.of(...) cannot be sorted in place. Copy it to an ArrayList first. For a class without Comparable, Collections.sort(list) fails its type check at compilation. Calling list.sort(null) on such objects fails at run time with ClassCastException when comparison is needed.

Collections.max(collection) and Collections.min(collection) find the largest and smallest natural-order elements without rearranging the collection. They throw NoSuchElementException for an empty collection.

For sorted map keys, either copy map.keySet() to an ArrayList and sort the copy, or use a TreeMap. Sorting a copied key list leaves the map's own iteration order unchanged.

Key Takeaways

  • Collections.sort changes a modifiable list in place and returns void.
  • String natural order compares characters, not numeric values in text.
  • Use ready-made comparators for reverse or case-insensitive order.
  • Stable sorting preserves the earlier relative order of tied elements.
  • Copy an unmodifiable list before sorting it.
  • min and max find extremes without sorting.

5.2 Implement Comparable in your own class

Java cannot guess whether a member should come first by name, height, or another field. Implement Comparable to give the class one natural ordering. Sorting code can then ask each object to compare itself with another object of that class.

Write the comparison method
class Member implements Comparable<Member> {
    private String name;
    private int height;

    Member(String name, int height) {
        this.name = name;
        this.height = height;
    }

    @Override
    public int compareTo(Member other) {
        return Integer.compare(this.height, other.height);
    }
}

Height is measured in centimeters. Comparable<Member> specifies that the other object is a Member; no cast is needed. public int compareTo(Member other) is the required method. The standard Comparable interface is in java.lang, so no import is needed for it.

For a.compareTo(b), a negative result places a before b, zero puts them at the same comparison position, and a positive result places a after b. Only the sign matters: -35 is just as valid a negative result as -1.

Follow the order

With the height comparison, Ana 172, Ben 165, and Cai 180 sort to Ben 165, Ana 172, and Cai 180. To put taller members first, swap the arguments:

return Integer.compare(other.height, this.height);

Change the rule deliberately. Reversing the arguments reverses that field's direction; it does not change what height means or alter any member's data.

Compare whole numeric values safely

Subtraction looks convenient but can return the wrong sign when an int overflows. For -2,000,000,000 and 2,000,000,000, subtracting the second from the first wraps to 294,967,296, a positive result. Integer.compare correctly returns a negative result.

For decimal fields, use Double.compare(this.price, other.price). Casting a difference to int loses information: (int) (1.8 - 1.5) is 0, so unequal prices become a comparison tie. A comparison helper preserves the ordering without truncating the difference.

Compare text and reuse the rule

For name order, return this.name.compareTo(other.name). It follows the string's character order. compareToIgnoreCase supplies case-insensitive text comparison when that is the intended field rule.

Once a class defines natural order, operations such as Collections.sort, Collections.max, and default TreeSet or TreeMap comparisons can use it. A class can implement other interfaces as well, separated by commas after implements.

There is one natural order for the class, not a different compareTo selected for every list. Use separate comparator objects when one context needs name order and another needs height order. A height-only comparison also ties all equal heights; deciding whether that tie is acceptable becomes especially important in sorted sets.

Key Takeaways

  • Implement Comparable<YourClass> with a public compareTo method.
  • Negative, zero, and positive results mean before, tied, and after.
  • Use Integer.compare and Double.compare for safe numeric ordering.
  • Swap comparison arguments to reverse a field’s direction.
  • One class has one natural order; comparators supply other orders.

5.3 Break ties and use sorted sets and maps

A primary comparison often leaves ties. Two films may share a year, or two players may share a score. A tie-breaker gives the next field a turn only when the earlier fields compare as equal.

Compare fields in priority order
@Override
public int compareTo(Film other) {
    int byYear = Integer.compare(this.year, other.year);
    if (byYear != 0) {
        return byYear;
    }
    return this.title.compareTo(other.title);
}

Year is the main rule. Title matters only when years tie. Up (2009), Avatar (2009), and Alien (1979) sort to Alien (1979), Avatar (2009), Up (2009). Comparing titles first would give them priority over year and answer a different sorting task.

Directions can differ by field. For points highest first and names A to Z, start with Integer.compare(other.points, this.points). On zero, return this.name.compareTo(other.name). Reversing the whole final list would reverse names within tied scores too.

Understand a sorted set's duplicate rule

A default TreeSet<Member> uses natural comparison both to order elements and to decide when an element is already present. If Member.compareTo uses only height, Ana 172 and Dee 172 compare as zero. Adding Ana returns true; adding Dee returns false. Ana remains the stored element even if equals considers the two members different.

A list can retain both tied objects; a tree set gives them one comparison position. Add the necessary tie-breaker if they must be distinct in the set.

Align comparison with equality

An order is consistent with equals when comparison returns zero if and only if equals returns true. For a class whose equality uses height and name, comparing height then name can meet this rule. If equality uses a different identity, such as a member ID, adding a name tie-breaker alone does not establish consistency.

The comparison must also behave like a proper order. If a comes before b, the reverse comparison must put b after a. If a is before b and b before c, a must be before c. Using whole-field comparison helpers in a fixed priority order supports these rules. An inconsistent method can misorder results or cause a sort to throw IllegalArgumentException.

Keep map keys sorted too

A TreeMap sorts keys, not values. For the word counts of "the cat saw the dog and the cat ran", the first key is "and" and the last is "the". firstKey() and lastKey() provide those extremes. Declare a TreeMap or an appropriate sorted-map interface when calling methods that plain Map does not declare.

Its key comparison also defines matching keys. A second key that compares as zero updates the existing mapping, even when equals distinguishes the objects. Default tree collections require naturally comparable elements or keys; inserting an object with no suitable comparison throws ClassCastException. An explicitly supplied comparator can define another order.

Key Takeaways

  • Compare the primary field first and consult later fields only on a tie.
  • Reverse only the fields that need descending order.
  • Tree collections treat comparison zero as the same element or key.
  • Consistency with equals requires comparison zero exactly when equality is true.
  • TreeMap sorts keys; its endpoint methods return extreme keys.
  • A comparison must reverse signs consistently and preserve order across triples.
6

Choose the right collection for a task

A collection choice starts with the questions the program must answer: by position, by membership, or by a separate key. Order and duplicates narrow the choice further. Once the data fits the task, compare how the frequent operations grow as more values arrive. A small change, such as making one set before a loop, can remove repeated searches without making the program harder to read.

6.1 Compare the cost of common collection operations

The cost of an operation describes how its work grows with the number of stored elements. It helps identify code that is quick for a small example but slow when the collection becomes large.

Compare growth, not seconds

Constant time, O(1), stays roughly independent of collection size. Linear time, O(n), can grow in proportion to the number of elements. Logarithmic time, O(log n), grows slowly as the size increases. These labels describe growth, not exact running times on a particular computer.

CollectionOperationCost
ArrayListget(i), set(i, x)Constant
ArrayListAppend at the endConstant on average
ArrayListcontains, indexOf, remove by valueLinear
ArrayListInsert or remove near the frontLinear
HashMap / HashSetBasic key lookup or membership, insert, removeConstant on average with well-spread hashes
TreeMap / TreeSetBasic lookup, insert, removeLogarithmic
LinkedListAdd or remove at either endConstant
LinkedListget(i) in generalLinear

An ArrayList search may check every element; front edits shift later elements. A LinkedList must walk to a position, so repeated indexed access can be expensive. ArrayList is a useful default for ordinary list work.

Spot the repeated scan

Suppose a program checks 10,000 names against a list containing 100,000 names. Calling list.contains(name) for each name can require up to 1,000,000,000 equality checks. A fast-looking method call is still a full search when used this way.

Build a membership set once:

Set<String> allowed = new HashSet<>(allowedNames);
int matches = 0;
for (String name : incomingNames) {
    if (allowed.contains(name)) {
        matches++;
    }
}

There is work to build the 100,000-element set, followed by 10,000 average constant-time membership checks. Counting both stages, the total grows roughly with the sum of the two input sizes, instead of their product. Rebuilding the set inside the loop would repeat the setup work and lose that benefit.

Read average guarantees correctly

Hash-based operations rely on keys whose hash codes spread values well. Returning one constant hash code for every object can still satisfy equality correctness, but makes lookup slow. It is not a free way to avoid writing a useful hash method.

Tree collections maintain sorted order with logarithmic basic operations. Doubling the number of elements adds only a small amount of search work. For 100,000 elements, a base-two logarithm is about 16.6; this suggests the scale of the search, not an exact guarantee of 17 comparisons in every Java tree lookup.

Account for the whole task

Building an extra set costs time and memory. For a few elements or one lookup, the original list may be enough. For repeated membership checks, one reusable set often removes the main cost. Start with required behavior, then inspect the operations repeated most often.

Key Takeaways

  • Growth labels describe scaling, not a measured number of seconds.
  • ArrayList gives quick indexed access but linear searches and front edits.
  • Hash lookups are constant on average with suitable hash codes; tree lookups are logarithmic.
  • Build a membership set once to replace repeated list scans.
  • Include setup time and memory when comparing whole solutions.

6.2 Pick a collection that fits the task

The right collection keeps the information the program needs and makes its main questions easy to express. Decide the data's rules before choosing a familiar class name.

Ask what identifies an item
Main needStarting choiceExample
Find a value by a separate keyMapProduct code to price
Test membership without duplicatesSetTaken usernames
Keep positions, order, or repeated itemsListA playlist that repeats songs
Keep a fixed number of slotsArrayTwelve monthly rainfall measurements

A double[12] can hold rainfall in millimeters when each slot has a known month. A map keyed only by positions 0, 1, 2, and so on adds a layer that a list or array already supplies.

Choose the order you need

For maps and sets, use HashMap or HashSet when no order is required, LinkedHashMap or LinkedHashSet for insertion order, and TreeMap or TreeSet for sorted keys or elements. For a general-purpose list, start with ArrayList.

Word counts printed alphabetically fit a TreeMap<String, Integer>. A first-seen list of distinct tags fits LinkedHashSet<String>. Repeated songs need a list even if the songs are also stored elsewhere in a set: discarding repeats would change the playlist.

Combine collections when the data has layers

Students per course can be Map<String, List<String>>; each value is an ordered list of enrollments. Tags per article can be Map<String, Set<String>>; each article gets distinct tags. A leaderboard can be a List<Player> sorted by the player's natural comparison.

The outer and inner choices answer different questions. If courses must be listed alphabetically and students kept in enrollment order, use a TreeMap outside and a list inside. Sorting the keys does not sort the lists. If duplicate enrollment records should be ignored, use a set for the inner groups instead.

Keep related data together

Two parallel lists, one for names and one for phone numbers, rely on matching positions. Removing a name without its number breaks every later pairing. If names uniquely identify people, a map can hold the association. If names repeat or several fields belong to one person, keep person objects in a list or index them by a unique ID.

Searching a list by a field over and over is another signal to consider an index map. Keep the list too if display order and repeated entries matter, but maintain both structures together when data is added or removed.

Check the element rules and the declared type

Use an interface declaration such as Map<String, Double> prices = new HashMap<>(); so callers rely on the map operations they need. Hash-based collections need meaningful equality and matching hash codes for custom keys or elements. Default tree collections need a natural comparison that distinguishes exactly the values the collection should keep. These rules are part of making the chosen collection represent the intended data.

Key Takeaways

  • Choose maps for keyed lookup, sets for membership, and lists for positions or repeats.
  • Arrays can hold a fixed number of slots, including primitive values.
  • Choose insertion or sorted order deliberately.
  • Nested collections let outer keys and inner groups follow different rules.
  • Keep related fields together and maintain multiple indexes through shared methods.
  • Match equality and comparison rules to the values the collection must keep.

HashMaps and Collections in Java examples

6 Walkthroughs

1

Follow a stock map from storage to lookup

13 steps
Trace changes, inspect entries safely, and make custom keys findable.
  1. 1
    IntroductionStart with a product question

    A stock program needs to answer "How many folders are available?" A map makes the product name the key and its quantity the value. Follow one map through replacement, a missing lookup, and cleanup. Then examine why a custom key can fail even when its fields look right. Each lookup depends on what Java considers the same key.

  2. 2
    ExplanationCreate one association per key

    Create HashMap<String, Integer> stock = new HashMap<>();. String describes the keys; Integer describes the values. The map uses reference types, so int cannot be the value type argument. Java boxes a literal such as 6 when stock.put("folder", 6) stores it. The diamond on the right lets Java infer the two types.

  3. 3
    ExampleReplace a quantity

    Run these updates in order:

    stock.put("folder", 6);
    stock.put("clip", 11);
    Integer old = stock.put("folder", 8);
    

    The last call finds the existing folder key, stores 8, and returns 6 into old. There are still two keys. A map records the latest value for a key; it does not automatically add quantities or keep a history of them.

  4. 4
    ChallengeRead without inserting

    What are n and stock.size() after this read? The map still has folder 8 and clip 11.

    int n = stock.getOrDefault("tape", 0);
    

    ---reveal---

    n is 0, and the size stays 2. The default is a result for a missing key, not an inserted entry. Reading with get("tape") instead returns null, which cannot be unboxed into an int.

  5. 5
    ExplanationRead pairs together

    An entry loop supplies each key and value together:

    for (Map.Entry<String, Integer> e : stock.entrySet()) {
        System.out.println(e.getKey() + ": " + e.getValue());
    }
    

    Import java.util.Map. The loop can show both associations without a separate get. If only a total is needed, loop over stock.values() and add the quantities; repeated quantities still contribute separately.

  6. 6
    Key InsightDo not infer the first entry

    The output might list folder before clip or clip before folder. HashMap promises neither order. A result such as a sum is unaffected, but a "keep the first tied score" rule can depend on traversal. Choose LinkedHashMap for insertion order or TreeMap for sorted keys, and give tied maxima an explicit tie rule when the winner must be predictable.

  7. 7
    ExampleDelete through the traversal

    Suppose folder is now 0 and clip is 11. Remove zero quantities with an iterator:

    Iterator<Map.Entry<String, Integer>> it =
        stock.entrySet().iterator();
    while (it.hasNext()) {
        if (it.next().getValue() == 0) {
            it.remove();
        }
    }
    

    The iterator removes its current entry and continues safely. Calling stock.remove from a for-each traversal can instead trigger ConcurrentModificationException.

  8. 8
    ChallengeSeparate a key copy

    Before cleanup, keys is created with new ArrayList<>(stock.keySet()). If keys.remove("folder") is called, what happens to the stock map?

    ---reveal---

    The map keeps its folder mapping. keys is a separate list of the keys that existed when it was copied. Removing from stock.keySet() itself would remove the map entry, because that object is a linked view.

  9. 9
    ExampleTry a custom key

    Imagine Bin has fields row and column and no equality overrides. Store a label using new Bin(3, 4), then look it up using another new Bin(3, 4). The lookup returns null. These are two different objects, and inherited Object.equals uses identity. Matching field values have not yet been made into a matching-key rule.

  10. 10
    ExplanationMake equality and hashing agree

    For coordinate-based bin identity, override equals(Object other) to compare row and column, and override hashCode() using the same fields, such as Objects.hash(row, column). Equal coordinates must produce equal hash codes. A matching hash code alone does not establish equality; the equality check still distinguishes different coordinate keys.

  11. 11
    ChallengeCatch an overload

    A class defines public boolean equals(Bin other) and hashCode() from its coordinates. Why can a lookup with a separate equal-looking bin still fail?

    ---reveal---

    The parameter must be Object to override Java’s equality method. The Bin-parameter method is an overload, leaving inherited identity equality in place. Adding @Override to that wrong signature makes the compiler expose the error.

  12. 12
    ChallengeRepair a changing-key design

    A bin key uses row and column in both equality methods. The program changes its row while stored, then cannot find its label. How should it update the location and then remove empty labels safely during traversal?

    ---reveal---

    Remove the mapping before changing the key, then reinsert it. For traversal cleanup, use the entry iterator’s own removal method. Stable key identity and safe traversal solve different parts of this update.

  13. 13
    RecapKeep a map update checklist

    For a missing lookup, decide whether a default or an explicit absence check fits the task. For a loop, decide whether order matters and whether keys will be removed. For a custom key, check the exact equals(Object) signature, matching hash fields, and stable identity. These checks locate different causes of the same symptom: a mapping that the program cannot use as expected.

2

Build attendance information as records arrive

12 steps
Count records, group distinct members, and keep lookup indexes consistent.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTurn arrivals into useful answers
  2. 2
    ExampleStart a session count
  3. 3
    ExampleSeparate distinct sessions from records
  4. 4
    ChallengeRepair a reset count
  5. 5
    ExplanationCreate a group once
  6. 6
    ExampleFollow the inner reference
  7. 7
    ChallengeFind the shared-group bug
  8. 8
    ExplanationIndex by an identifying key
  9. 9
    Key InsightChange one object in several places
  10. 10
    ChallengeKeep removal consistent
  11. 11
    ChallengeCombine counts with distinct membership
  12. 12
    RecapCheck a first arrival and a repeat
3

Compare two attendance groups

9 steps
Use set membership, preserve originals, and report the right difference.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk who, not how many visits
  2. 2
    ExampleCollapse repeated scans
  3. 3
    ChallengeStop at the first repeated arrival
  4. 4
    ExampleKeep only shared members
  5. 5
    ExplanationChoose the direction of difference
  6. 6
    ChallengeTest a selected group
  7. 7
    TipChoose a useful report order
  8. 8
    ChallengeMake a sorted missing-attendance report
  9. 9
    RecapRead the receiver as the starting group
4

Read collection declarations and copies

10 steps
Use interfaces, diagnose overloads, and separate structure from shared objects.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionRead both sides of the declaration
  2. 2
    ExplanationDeclare what the caller needs
  3. 3
    ExampleUse a wider parameter for reading
  4. 4
    ChallengeDiagnose the missing method
  5. 5
    ConnectionChoose the meaning of contents
  6. 6
    ExampleFollow integer removal
  7. 7
    ChallengeCopy before sorting
  8. 8
    Key InsightSeparate object edits from list edits
  9. 9
    ChallengePass the right map view
  10. 10
    RecapCheck type, operation, and object
5

Build a ranking that keeps the right ties

15 steps
Sort strings and objects, write safe comparisons, and check sorted-set membership.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose what comes first
  2. 2
    ExampleSort the same list
  3. 3
    ExplanationRead the first differing character
  4. 4
    ChallengeUse a supplied order
  5. 5
    ExplanationGive a class one natural order
  6. 6
    ExampleAvoid a numeric false tie
  7. 7
    ChallengeReverse the numeric field
  8. 8
    ExampleBreak only genuine ties
  9. 9
    ExampleWork through the ranking
  10. 10
    ChallengeSee what a tree set retains
  11. 11
    Key InsightMatch ordering to identity
  12. 12
    ConnectionCheck a sorted map’s key
  13. 13
    ChallengeKeep every result in a ranked list
  14. 14
    TipMake the rule work across triples
  15. 15
    RecapCheck a comparison in two places
6

Choose structures for a course roster

10 steps
Match lookup, membership, ordering, and cost without repeated scans.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionList the questions the program asks
  2. 2
    ExampleNotice the scan inside the loop
  3. 3
    ExplanationBuild membership support once
  4. 4
    ChallengeCompare growing inputs
  5. 5
    ExampleKeep repeated enrollment records
  6. 6
    ExplanationChoose outer and inner order
  7. 7
    ChallengeRepair the wrong duplicate rule
  8. 8
    TipPay for the order you need
  9. 9
    ChallengeCombine the final design
  10. 10
    RecapChoose behavior before measuring speed

HashMaps and Collections in Java practice questions

50 Practice Questions in 5 sets

Set 1: Read and update maps reliably10 Practice Questions

Question 1 of 10

An empty HashMap<String, Integer> receives put("brush", 5) and then put("brush", 14). What are its size and the value for "brush"?
  1. Size 2; value 14.
  2. Size 1; value 14.
  3. Size 1; value 19.
  4. Size 2; value 5.
Show answerHide answer
Answer: B
Both updates use the same key, so the second replaces the first value and the map keeps one entry. The value is 14, not 19: put does not add the incoming quantity to the previous quantity. Accumulation needs a read-and-update expression.

Question 2 of 10

A non-null quantity map has no key "tray". What happens when int n = map.get("tray"); runs?
  1. It stores 0 in n and continues.
  2. It throws ClassCastException.
  3. It inserts "tray" with value 0.
  4. It throws NullPointerException.
Show answerHide answer
Answer: D
A missing get returns null, and assigning that result to an int attempts to unbox it. Null has no primitive integer value, so Java throws NullPointerException. The map does not supply zero or create a quantity merely because the destination variable is numeric.

Question 3 of 10

A loop must read each device ID together with its status from a map. What view supplies both in one loop element?
  1. entrySet()
  2. keySet()
  3. values()
  4. map.keySet().toArray()
Show answerHide answer
Answer: A
entrySet() supplies an entry containing both a key and its associated value. A key loop can recover the value with another lookup, but the key-set element itself supplies only the key. The values view cannot identify which key belongs to each status.

Question 4 of 10

Two separate objects are equal under a correct equals method. What must their hash codes be?
  1. Different integer values.
  2. Their numbers of fields.
  3. The same integer value.
  4. Their memory addresses.
Show answerHide answer
Answer: C
Equal objects must return equal hash codes so a hash-based collection can find them under the same matching rule. Different hash codes for equal objects violate that contract. The reverse implication is false: two unequal objects are allowed to share a hash code.

Question 5 of 10

A map contains "beam" → 9. The program executes Integer old = map.put("beam", 13); and then Integer removed = map.remove("beam");. What are old, removed, and the final size?
  1. 13, 13, and 0.
  2. 9, 9, and 0.
  3. 9, 13, and 1.
  4. 9, 13, and 0.
Show answerHide answer
Answer: D
The replacement returns the earlier value 9, while the entry now stores 13. Removal therefore returns 13 and deletes the only entry, leaving size 0. Treating the first result as 13 confuses the value put returns with the value it stores.

Question 6 of 10

A stock-cleanup loop traverses entrySet() and must delete each zero-valued entry. How should it remove the entry during traversal?
  1. Use that traversal’s iterator and call its remove() after next().
  2. Use a for-each loop and call the map’s remove() with each zero key.
  3. Use an entry loop and replace every zero value with null.
  4. Use a values loop and remove each zero key from keySet() directly.
Show answerHide answer
Answer: A
The iterator’s own removal method coordinates deletion with its current traversal position. Direct removal through the map or a linked view changes the structure behind the traversal and can trigger ConcurrentModificationException. Replacing a quantity with null would not delete the entry.

Question 7 of 10

A Cell class defines equals(Cell other) and a field-based hashCode. Separate cells with equal fields fail to match as HashMap keys. What method change addresses the equality error?
  1. Keep equals(Cell other) and return one constant hash code.
  2. Override equals(Object other) with the same field comparisons.
  3. Replace the equality method with a field-based toString().
  4. Add compareTo(Cell other) without changing either equality method.
Show answerHide answer
Answer: B
A map uses equals(Object), so the Cell-parameter method is an overload and leaves inherited identity equality in place. Override the Object-parameter method and use matching fields in hashing. Changing the hash code alone cannot make the wrong equality method participate in lookup.

Question 8 of 10

A HashMap search records a key only when its score is strictly greater than the best score so far. Two keys tie for the highest score. What result can the program promise?
  1. One of the tied keys, without a promised tie order.
  2. The tied key inserted earliest into the map.
  3. The tied key alphabetically earliest by name.
  4. The tied key inserted most recently into the map.
Show answerHide answer
Answer: A
The search keeps whichever tied key it visits first, because an equal score does not pass the strict greater-than test. A HashMap does not promise insertion or alphabetical traversal order. A predictable tie result requires an explicit tie rule or an order chosen for that purpose.

Question 9 of 10

A map starts with "ink" → 4 and "paper" → 0. keys is a new ArrayList copied from its key set. The program removes "ink" from keys, removes "paper" through the map’s key-set view, then doubles all remaining map values. What is left in the map?
  1. Only "paper" → 0.
  2. No mappings remain.
  3. Only "ink" → 8.
  4. Both "ink" → 8 and "paper" → 0.
Show answerHide answer
Answer: C
The copied list is independent, so removing ink there leaves its mapping intact. The key-set view is linked, so removing paper there deletes that mapping. Doubling the surviving ink value gives 8; treating the copied list as another linked view would incorrectly remove both entries.

Question 10 of 10

Location equality and hashing use a mutable coordinate. A key is stored, then its coordinate is changed while stored; its mapping is now missed by lookup. What update sequence should the design use to prevent this failure?
  1. Change the coordinate; get by the new coordinate; reinsert.
  2. Remove before mutation; change the coordinate; reinsert.
  3. Change the coordinate; replace equals; get by old coordinate.
  4. Keep a second reference; change the coordinate; look up with it.
Show answerHide answer
Answer: B
Removal must happen while the key still has the equality and hash identity used for insertion. The program can then change it and reinsert under the new identity. Looking up with the same reference after mutation is not a repair: the changed hash can still lead away from the stored entry.
Set 2: Build counts and compare groups10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

The sequence is [12, 7, 4, 12, 7]. A loop stops at the first !seen.add(n). What number is reported?
  1. 7
  2. 4
  3. 12
  4. No number.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A frequency map records "north" → 4, "south" → 2, and "west" → 3. How many distinct keys does it contain?
  1. 9
  2. 4
  3. 3
  4. 2
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A HashSet already contains "cedar". What does another add("cedar") return?
  1. false
  2. true
  3. null
  4. The stored string.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A course must list each participant only once even when duplicate registration records arrive. What inner collection rule fits each course group?
  1. A list of participant IDs.
  2. An integer count of records.
  3. One participant ID as a string.
  4. A set of participant IDs.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

The loop processes "red", "gold", "red", "blue", "gold", "red" using counts.put(word, counts.getOrDefault(word, 0) + 1). What are the red count and map size?
  1. Red count 1; size 3.
  2. Red count 3; size 3.
  3. Red count 3; size 6.
  4. Red count 6; size 3.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Inside a grouping loop, every arrival runs groups.put(team, new ArrayList<>()); followed by groups.get(team).add(name);. A team receives Omar, Pia, then Ren. What remains under that team?
  1. [Omar, Pia, Ren]
  2. [Ren]
  3. [Omar]
  4. An empty list.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A = {2, 5, 8, 11} and B = {5, 11, 14}. A copied set C starts with A, then runs C.removeAll(B). What does C contain?
  1. {5, 11}
  2. {14}
  3. {2, 5, 8, 11, 14}
  4. {2, 8}
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

The same Device object is stored in a list and an ID map. It is retrieved from the map, then its status field changes. What status does the list’s stored reference expose?
  1. The changed status on the same object.
  2. The original status in a separate copied object.
  3. Null until the list entry is replaced.
  4. The changed status only after a second map put.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

One ArrayList is stored under both "Morning" and "Evening". The program adds "Lee" through Morning, then replaces Evening’s mapping with a fresh list and adds "Jo" through Evening. What are the final groups?
  1. Morning [Lee]; Evening [Jo].
  2. Morning [Lee, Jo]; Evening [Lee, Jo].
  3. Morning []; Evening [Lee, Jo].
  4. Morning [Jo]; Evening [Jo].
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A = {1, 3, 6} and B = {3, 6, 9}. C is copied from A and runs retainAll(B). D is copied from B and runs removeAll(C). What are D and the result of A.containsAll(C)?
  1. D = {1}; the result is true.
  2. D = {9}; the result is false.
  3. D = {3, 6, 9}; the result is false.
  4. D = {9}; the result is true.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Diagnose collection behavior10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A program stores rainfall in millimeters in one slot for each of the twelve months. It needs a fixed number of primitive numeric slots. What structure fits directly?
  1. A Set<Double> of readings.
  2. A double[12] array.
  3. A Map<Double, String> of months.
  4. A HashSet<Integer> of month numbers.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A HashMap contains the key "pending" explicitly mapped to null. What does getOrDefault("pending", 20) return?
  1. 20
  2. 0
  3. null
  4. An exception from the lookup itself.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What happens when Set.of("draft", "final", "draft") is evaluated?
  1. It throws IllegalArgumentException.
  2. It returns a set containing two elements.
  3. It returns a list containing three elements.
  4. It throws UnsupportedOperationException.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A member index uses display names as keys. Two different members named "Ari Chen" are inserted, and the first can no longer be retrieved by that name. What design directly preserves both for individual lookup?
  1. Keep the name key but use TreeMap.
  2. Keep the name key in a LinkedHashMap.
  3. Call put again with the same name.
  4. Index by each member’s unique ID.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A mutable list currently contains [10, 2, 7]. After Collections.reverse(list), what is its content?
  1. [10, 7, 2]
  2. [2, 7, 10]
  3. [7, 10, 2]
  4. [7, 2, 10]
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A program repeatedly checks whether IDs occur in a large ArrayList and does not need positions for those checks. What change avoids repeating the full search work?
  1. Build a new HashSet inside the query loop.
  2. Copy the ArrayList once into a LinkedList.
  3. Build one HashSet before the query loop.
  4. Sort a fresh ArrayList for every query.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A grouping map has no key "Support". The program evaluates List<String> result = groups.getOrDefault("Support", new ArrayList<>()); and then adds "Nia" to result. A later groups.get("Support") returns what?
  1. null, because the default was never inserted.
  2. A list containing Nia, because the default became the group.
  3. An empty list, because the default was stored before the addition.
  4. An exception, because an unstored default list cannot be modified.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

ScoreKey equality uses team and points; its natural comparison uses only points. A default TreeMap gets key East-30 with value "old", West-30 with value "new", then North-18 with value "low". What are its size and the value found using East-30?
  1. Size 3; the value is "old".
  2. Size 2; the value is "new".
  3. Size 2; the value is "old".
  4. Size 1; the value is "low".
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A = {4, 7, 10} and B = {7, 10, 13}. A copy U first runs addAll(B), then removeAll(A). What is U, and did either original change?
  1. U = {4}; both originals are unchanged.
  2. U = {4, 13}; only A is changed.
  3. U = {7, 10}; only B is changed.
  4. U = {13}; both originals are unchanged.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A report needs courses alphabetically and each course’s distinct member IDs in first-registration order. What outer and inner implementations fit together?
  1. TreeMap outside; LinkedHashSet inside.
  2. LinkedHashMap outside; TreeSet inside.
  3. TreeMap outside; ArrayList inside.
  4. HashMap outside; LinkedHashSet inside.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Combine lookup, grouping, and order10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A player class defines equality by name and score and compares score descending, then name ascending. A default TreeSet receives Mira 9, Axel 12, Mira 9, and Bo 9 as separate objects. What ordered membership results?
  1. Axel 12, Mira 9, Bo 9.
  2. Axel 12, Mira 9, Mira 9, Bo 9.
  3. Bo 9, Mira 9, Axel 12.
  4. Axel 12, Bo 9, Mira 9.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What determines equality between an ArrayList and a LinkedList holding the same element values?
  1. The values must appear in the same order.
  2. The lists must have the same concrete class.
  3. Only the number of distinct values must match.
  4. The element references must all be identical.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

An initially empty totals map processes repairs 4.25, delivery 2.50, and repairs 3.75 using a zero-default addition. What are its size and repairs total?
  1. Size 3; repairs total 8.00.
  2. Size 2; repairs total 3.75.
  3. Size 2; repairs total 10.50.
  4. Size 2; repairs total 8.00.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

An equality-correct custom class returns the same hash code for every instance. What happens to HashSet correctness and lookup performance?
  1. Every value merges into one element, making lookup faster.
  2. Distinct unequal values remain valid, but lookups can slow down.
  3. Distinct values remain valid, with constant-time lookup guaranteed.
  4. Every insertion fails at compilation because hash codes repeat.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A temperature class must compare two double fields in ascending order without false ties from a cast. What return expression fits?
  1. (int) (this.value - other.value)
  2. Double.compare(other.value, this.value)
  3. Double.compare(this.value, other.value)
  4. Integer.compare((int) this.value, (int) other.value)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A map contains two different keys each mapped to 6. What total does summing map.values() produce?
  1. 12
  2. 6
  3. 2
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A catalog keeps the same Item objects in an ID index and a category-to-list index. An item’s category changes from Cables to Adapters. Changing its category field alone leaves it in the Cables list. What update keeps the indexes consistent?
  1. Replace it in the ID map; leave both category lists as they are.
  2. Change the ID map to TreeMap; keep both category lists as they are.
  3. Move its reference between category lists; keep its ID mapping.
  4. Copy the item under the old category; clear its ID mapping.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A program has an allowed list and a query list. Both sizes double. Compare repeated full list searches with building one HashSet of allowed values and then querying it, under suitable hashing. How does their total work grow?
  1. Both totals can quadruple because both inputs contain twice as many values.
  2. List-search work can quadruple; set-build-plus-query work roughly doubles.
  3. List-search work roughly doubles; set-build-plus-query work stays constant.
  4. Both totals stay constant because each uses one method call per query.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A map groups notes by project. Two projects must keep independent lists, repeated notes, and arrival order. Existing code creates one shared ArrayList, puts it under every new key, and adds notes through get. What complete repair preserves the requirements?
  1. Keep the shared ArrayList, but replace each get with getOrDefault using that same list.
  2. Create a fresh ArrayList for each new key, then append through its stored reference.
  3. Create a fresh HashSet for each new key, then add notes through its stored reference.
  4. Create a new empty ArrayList for the project on every arrival, then append the current note.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A document system needs unique tags in first-seen order, direct object lookup by unique document ID, and a separate ordered history that retains repeat visits. What structures fit the three needs?
  1. TreeSet for tags; List for ID lookup; HashSet for history.
  2. HashSet for tags; Map for ID lookup; TreeSet for history.
  3. LinkedHashSet for tags; Set for ID lookup; Map keyed by document ID for history.
  4. LinkedHashSet for tags; Map for ID lookup; List for history.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Use interfaces and sort data10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

In Set<String> codes = new HashSet<>();, what is the declared type of codes?
  1. HashSet<String>
  2. String
  3. Collection<HashSet>
  4. Set<String>
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does a positive value returned by a.compareTo(b) mean?
  1. a comes before b in that order.
  2. a and b are tied in that order.
  3. a comes after b in that order.
  4. a has one greater numeric field.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A mutable List<Integer> starts as [4, 8, 12]. It runs remove(1). What remains?
  1. [4, 12]
  2. [8, 12]
  3. [4, 8]
  4. [4, 8, 12]
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What is the natural sorted order of the strings "zebra", "Apron", "18", "3", "ant"?
  1. ["3", "18", "ant", "Apron", "zebra"]
  2. ["18", "3", "Apron", "ant", "zebra"]
  3. ["18", "3", "ant", "Apron", "zebra"]
  4. ["Apron", "ant", "zebra", "18", "3"]
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A read-only method accepts Collection<String>. A caller has Map<String, String> labels and wants the method to process each label value. What should be passed?
  1. labels.values()
  2. labels
  3. labels.entrySet()
  4. labels.keySet().iterator()
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A price comparison returns (int) (this.price - other.price). What goes wrong for prices 6.8 and 6.3?
  1. It always places 6.8 before 6.3.
  2. It overflows the int range.
  3. It returns zero for unequal prices.
  4. It changes both stored prices to integers.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Results must sort by points highest first and then name A to Z. The primary comparison is nonzero. What should compareTo do next?
  1. Compare the names and return it.
  2. Return zero to keep input order.
  3. Return a negated name comparison.
  4. Return that primary comparison.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A modifiable list contains one mutable Ticket object. A second ArrayList is copied from it. The program changes the ticket’s label through the copy, then clears the copy. What does the original list contain?
  1. An empty list with no ticket left in it.
  2. The same ticket with its changed label.
  3. A separate ticket with its original label.
  4. The same ticket with its original label.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A class compares by descending level, then ascending code. The records are Delta 2, Beta 4, Alpha 2, and Echo 4. What order results?
  1. Echo 4, Beta 4, Delta 2, Alpha 2.
  2. Alpha 2, Beta 4, Delta 2, Echo 4.
  3. Beta 4, Echo 4, Alpha 2, Delta 2.
  4. Alpha 2, Delta 2, Beta 4, Echo 4.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Reading.equals uses station ID and temperature, but its natural comparison uses only temperature. A default TreeSet receives A at 16, B at 16, then C at 12. What are its size and the retained IDs?
  1. Size 2; IDs C and A.
  2. Size 3; IDs C, A, and B.
  3. Size 2; IDs C and B.
  4. Size 1; ID C only.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

70 Key Terms, each with its definition

A

Array
An array stores a fixed number of indexed elements of one type and can hold primitive values directly without wrapper type arguments.
A double[12] can give each month one slot for its rainfall measurement in millimeters.
Autoboxing
Autoboxing is Java’s automatic conversion of a primitive value to its corresponding wrapper object when an object is required.
Putting the literal 12 into a map of Integer values automatically boxes that number for storage.

C

Character order
Character order compares strings at their first differing UTF-16 code unit, with a shorter matching prefix placed first.
In the examples "7", "Bee", and "ant", natural string order places the digit before the letters.
Collection
Collection is the shared Java interface for groups of elements, extended by List and Set but separate from the Map interface.
A read-only word-counting method can accept a Collection<String> and iterate over either a list or a set.
Collection choice
A collection choice matches required positions, duplicates, key lookup, and order to an interface and a suitable implementation.
An alphabetical count report and an ordered playlist need different structures because they preserve different information.
Collection view
A collection view exposes part of another structure through a collection interface, with changes linked to the underlying structure.
Removing a product through the stock map’s key set removes the matching entry from the map itself.
Comparable
Comparable is the Java interface through which a class defines its natural order by implementing a typed compareTo method.
A member class can implement Comparable<Member> so list sorting can order its instances by height.
Comparator
A comparator is an object supplying a comparison rule that can differ from a class’s natural order, such as reverse or case-insensitive order.
String.CASE_INSENSITIVE_ORDER sorts a list without changing the capitalization stored in each string.
compareTo
The compareTo method returns a negative integer, zero, or a positive integer to place this object before, tied with, or after another.
A result of -8 places the left object before the right just as a result of -1 would do.
Consistency with equals
Consistency with equals means comparison returns zero exactly when equality returns true, so both rules identify the same values.
A tree set needs its member comparison to distinguish the same identities as the member’s equality rule.
Constant time
Constant time describes work that stays roughly independent of element count; hash-based basic operations have this cost on average under suitable hashing.
Reading one ArrayList position does not require scanning all the earlier positions in that list.
Content equality
Content equality treats separate objects as equal when their chosen data matches, using an appropriate override of equals(Object).
Two separately created coordinate keys can find the same label when their equality compares both coordinates.

D

Declared type
A variable’s declared type determines which methods the compiler allows through that variable, even when its object has extra methods.
An ArrayList stored in a List variable cannot expose ensureCapacity through that variable.
Diamond syntax
Diamond syntax uses empty angle brackets on a constructor so Java can infer its type arguments from the surrounding declaration.
In HashMap<String, Integer> m = new HashMap<>();, the diamond avoids repeating the two types.
Distinct item
A distinct item is one value considered different under the collection’s matching rule, regardless of how often that value occurs.
A frequency map for "sun rain sun" contains two distinct word keys but records three occurrences.
Duplicate arrival
A duplicate arrival is an input occurrence whose equal value has already been seen; a seen set detects it when add returns false.
In the sequence 6, 9, 2, 9, 6, the second 9 is the first arrival that repeats an earlier value.

E

Encapsulation
Encapsulation keeps data inside a class and exposes controlled methods, so the class can maintain rules about updates and lookup.
A library class can keep its indexes private so that its addBook method updates them together instead of callers editing them.

F

Frequency table
A frequency table links each distinct item to its number of occurrences, commonly using map keys for items and integer values for counts.
A word-count map distinguishes the number of different words from the total number of word occurrences.

G

getOrDefault
The getOrDefault method returns the value associated with a key, or the supplied default when no mapping for that key exists.
Reading a missing count with a zero default gives 0 without creating a new entry in the count map.
Grouping
Grouping collects items with a shared property under one map key, using a list or set as the value that stores each group.
A course key can lead to a list of students, while a first-letter key can lead to matching words.

H

Hash-code contract
The hash-code contract requires objects that are equal under equals to return equal hash codes, while allowing collisions for unequal objects.
Coordinate keys use the same x and y fields in both their equality test and their hash-code method.
HashMap
A HashMap is a modifiable Java map that stores unique keys with associated values and promises no particular iteration order.
A HashMap<String, Integer> can look up the current count for a product without using a list position.
HashSet
A HashSet is a modifiable Java set with average constant-time basic operations under suitable hashing and no guaranteed iteration order.
A HashSet<String> can track names already processed while a program reads a longer input sequence.

I

Identity equality
Identity equality treats objects as equal only when they are the same instance, which is the equality inherited from Object.
Without overrides, a newly constructed point does not match a stored point with identical coordinates.
Implementation
An implementation is a concrete class that supplies an interface’s operations and determines the behavior of the object created.
HashMap and TreeMap both implement Map, but they make different promises about key order.
In-place sort
An in-place sort rearranges the supplied list itself instead of returning a separate sorted list for the caller to assign.
After Collections.sort(values), the existing list variable exposes its elements in their new order.
Index
An index is a map from an identifying key to an object, allowing lookup by that key without repeatedly searching a list of objects.
A library’s ISBN index can return the same book object that also appears in its all-books list.
Integer overflow
Integer overflow occurs when an arithmetic result exceeds the int range and wraps, which can give subtraction-based comparisons the wrong sign.
Comparing extreme int fields with Integer.compare avoids the sign reversal that subtraction can cause.
Interface
An interface declares operations that implementing classes provide, allowing a variable or parameter to state the capabilities it needs.
A method accepting List<String> can receive an ArrayList or a LinkedList without changing its signature.
Interface parameter
An interface parameter accepts objects through the operations promised by an interface instead of requiring one concrete implementation.
A reporting method can accept Map<String, Integer> while callers choose hash or tree storage.
Intersection
The intersection of two sets contains only the elements shared by both; retainAll removes unshared values from its receiver.
Keeping only Tuesday’s names in a copy of Monday’s set finds the people who attended both days.
Iteration order
Iteration order is the sequence in which a traversal visits elements or entries; some implementations promise one and others do not.
A tied-score search needs an explicit tie rule if its result must be independent of HashMap traversal.
Iterator
An iterator tracks a traversal through a collection and supplies methods to test for and retrieve the next element.
A stock-cleanup loop uses hasNext(), next(), and the iterator’s remove() to delete zero quantities.

K

Key normalization
Key normalization applies a consistent cleanup rule before storage and lookup so equivalent input forms use the same map key.
A word counter can lowercase tokens and remove punctuation before adding each occurrence to its map.
Key–value pair
A key–value pair links an identifying key to one associated value in a map, such as a product code linked to a quantity.
In a stock map, the pair "pen" → 18 connects a product name to the number currently available.
Keyed lookup
A keyed lookup finds a value through a separate identifier, making a map useful when repeated searches would otherwise inspect object fields.
A product-code map answers price queries directly while a list would need a search for the matching code.

L

Linear time
Linear time describes work that can grow in proportion to the number of elements, as when a search may inspect the entire collection.
Repeated membership checks against a long list can repeatedly pay for scans of the same stored names.
LinkedHashMap
A LinkedHashMap is a map whose ordinary insertion-ordered form visits keys in insertion order while retaining the usual map operations.
Replacing a stored price keeps that product’s place in an insertion-ordered LinkedHashMap.
LinkedHashSet
A LinkedHashSet stores distinct elements while preserving their insertion order, including first-occurrence order when copied from a list.
A tag list copied into a LinkedHashSet loses repeats while keeping the order in which tags first appeared.
List
A List stores elements in an indexed sequence starting at zero, permits duplicates, and compares equality using the full element order.
A playlist uses list positions to keep two occurrences of the same song at different points in the sequence.
Logarithmic time
Logarithmic time describes work that grows slowly with element count, as in the guaranteed basic lookup costs of tree maps and sets.
A tree map keeps keys sorted while avoiding a full scan for each ordinary key lookup.
Lookup table
A lookup table maps codes or names to associated data that a program retrieves when processing another task.
An order calculator reads product prices from a table before adding each product’s contribution.

M

Map
A Map associates unique keys with values, allowing repeated values while each key has at most one associated value at a time.
Two products may both map to price 3.50 without violating the requirement that their keys be unique.
Map.Entry
A Map.Entry represents one key–value association and gives access to its key and value together during map traversal.
An entry loop can print a player’s name and score without looking the score up again by name.
Membership
Membership describes whether a value belongs to a set, as tested by contains using that set’s matching rule.
A username-checking program tests membership before accepting a new name into its taken-name set.
Mutable key
A mutable key has data that can change; changing fields used in its equality or hash code while it is stored can break map lookup.
A coordinate key is safer with final fields than with setters that can change its stored identity.

N

Natural order
A natural order is the default comparison supplied by a class, such as ascending numeric order or character-based string order.
Sorting strings "20" and "3" places "20" first because the initial characters decide their order.
Nested collection
A nested collection stores collections inside another structure, so outer keys and inner members can follow separate rules.
A sorted course map can hold insertion-ordered student lists without sorting the students themselves.

O

Overload
An overload is a method sharing a name with another method but using different parameters, allowing Java to choose a different operation.
For an integer list, remove(1) selects index removal while remove(Integer.valueOf(1)) selects value removal.

P

Parallel lists
Parallel lists store associated fields at matching indexes in separate lists, making the relationship depend on coordinated structural edits.
Removing a person’s name without removing the number at the same index misaligns later phone-book entries.
putIfAbsent
The putIfAbsent method stores a value when a key has no non-null mapping and otherwise keeps the value already associated with that key.
Before adding a grouped item, putIfAbsent can ensure that its key has a list without replacing an existing one.

R

Running total
A running total is an accumulated amount that is updated by adding each new contribution to the amount already stored.
An expense map reads the old category total, adds the next amount, and stores the increased result.

S

Set
A set is a collection of distinct elements that provides membership operations without the indexed positions supplied by a list.
A set of visited cities keeps one entry for each city even when a traveler returns several times.
Set difference
A set difference contains elements in the first set that are absent from the second, so reversing the sets can change the result.
Removing Tuesday’s attendees from a Monday copy finds Monday-only attendees, not Tuesday-only attendees.
Setup cost
A setup cost is the work needed to build a supporting structure before later operations can benefit from using it.
A membership set should be built once before many checks, with its construction included in the total work.
Shallow copy
A shallow copy creates a separate collection structure containing the same element references instead of duplicating the stored objects.
Removing a book from a copied list leaves the source list intact, but both lists can still refer to the same book.
Shared reference
A shared reference lets two variables or entries reach the same object, so a change to that object is visible through either reference.
Two course keys assigned one list object will both show a student added through only one of those keys.
Stable sort
A stable sort preserves the relative input order of elements that compare as equal under the comparison used for that sort.
Two players tied by a score-only comparison remain in their earlier relative order after a stable list sort.
Structural modification
A structural modification changes a map’s set of keys, as when a new mapping is added or an existing mapping is removed.
Replacing the quantity for a key already present changes its value without structurally changing the map.
Subset
A subset has every one of its elements in another set, which may contain additional elements; a.containsAll(b) tests b within a.
A selected group is a subset of an attendee set when every selected person appears on that event’s list.

T

Tie-breaker
A tie-breaker is a secondary comparison used only when earlier comparison fields tie, preserving their priority in the overall order.
A year-then-title film comparison consults titles only for films released in the same year.
Transitivity
Transitivity requires an ordering to place a before c whenever it places a before b and b before c, keeping comparisons coherent.
Comparing fields in a fixed priority order avoids a cycle in which each of three objects precedes another.
TreeMap
A TreeMap keeps mappings ordered by their keys and uses key comparison to identify an existing mapping during lookup or replacement.
Alphabetical word-count reporting can use a tree map whose smallest key is available through firstKey().
TreeSet
A TreeSet keeps elements sorted and uses its comparison result to decide whether an element is already present in the set.
A height-only member comparison makes two different members with equal heights compete for one set position.
Truncation
Truncation discards a decimal fraction when a value is cast to int, potentially turning a small nonzero comparison difference into zero.
Casting the price difference between 2.7 and 2.2 to int gives a false tie instead of a positive comparison.

U

Unboxing
Unboxing is Java’s automatic conversion from a wrapper object to a primitive value; attempting it with null throws an exception.
Assigning a missing Integer lookup to an int fails because the returned null cannot be unboxed.
Union
The union of two sets contains every element present in either set; Java’s addAll forms it by changing the receiving set.
Copying Monday’s attendee set and adding Tuesday’s gives everyone who came on at least one day.
Unique identifier
A unique identifier distinguishes each object within the data being indexed, preventing separate records from competing for the same map key.
A member ID keeps two people with the same display name in separate entries of a membership index.
Unmodifiable collection
An unmodifiable collection rejects structural or replacement edits through its API, while objects it contains can still be mutable.
A list from List.of must be copied before sorting, but a stored mutable object is not frozen by that list.

W

Wrapper class
A wrapper class provides an object type for a primitive value, allowing numbers and other primitive data to be used as collection type arguments.
A quantity map uses Integer as its value type because int cannot appear as a generic type argument.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started