Java Questions 111 -120  «Prev  Next»


Java SE 25: Lists, Sets, and Key Equality

Compare list and array costs, select hash or sorted sets, and understand how different map implementations recognize keys in Java SE 25.

  1. How do LinkedList and ArrayList differ?

    Answer: ArrayList stores elements in a resizable array; LinkedList stores a doubly linked sequence of nodes. ArrayList supports constant-time indexed access, while LinkedList traverses from the nearer end to find an index. ArrayList insertion or removal within its sequence shifts elements.

    LinkedList can link or unlink a node in constant time once the position is known, but locating an arbitrary insertion point takes time. Node storage adds overhead. Neither implementation is synchronized.

  2. Which data structures can LinkedList represent?

    Answer: LinkedList implements both List and Deque, so it can serve as a positional list, FIFO queue, or LIFO stack. Use offer/poll for ordinary queue operations or push/pop for stack operations. For many end-based workloads, ArrayDeque is also a useful choice and avoids per-element linked nodes.

    LinkedList permits null, but using null as a queued value conflicts with poll and peek using null to signal emptiness. ArrayDeque rejects null.

  3. Are arrays always faster than lists?

    Answer: No. Performance depends on the operation, implementation, element representation, and workload. Arrays have fixed length and support direct indexed access; ArrayList also provides constant-time indexed access plus resizing. An int array stores primitive values, whereas a List<Integer> stores references and involves boxing.

    Neither array nor list is universally faster. A linked list avoids shifting after a known node, but finding that node may dominate the operation. Compare equivalent operations and realistic data rather than making blanket claims.

  4. What are the main characteristics of HashSet?

    Answer: HashSet enforces uniqueness using equality and hashing, permits one null element, and makes no encounter-order guarantee. Its add, contains, and remove operations have expected constant-time performance with well-distributed hashes. Iteration cost also depends on the backing table capacity.

    It is not synchronized. Concurrent mutation requires a suitable synchronization strategy or a concurrent set implementation. Fail-fast iteration is a best-effort bug detector, not a thread-safety guarantee.

  5. When is HashSet a good choice?

    Answer: Use it for membership checks or duplicate elimination when no iteration order is required. For example, a set of immutable identifiers can track which records have already been processed. Use LinkedHashSet for predictable encounter order, TreeSet for sorted navigation, or EnumSet for enum values.

  6. What does LinkedHashSet add to HashSet behavior?

    Answer: It maintains encounter-order links as well as hash-based membership. Normal add operations retain insertion order; explicit first/last operations can reposition elements. In Java SE 25 it implements SequencedSet and exposes a reversed view. Both classes use the same equality/hash requirements.

  7. Which should you choose for predictable insertion-order traversal?

    Answer: Choose LinkedHashSet over HashSet. It provides the documented ordering guarantee. If you need sorted order rather than insertion order, choose a sorted set instead.

    import java.util.HashSet;
    import java.util.LinkedHashSet;
    import java.util.List;
    import java.util.TreeSet;
    
    public class SetChoices {
        public static void main(String[] args) {
            List<String> source = List.of("B", "A", "B");
            var hashed = new HashSet<>(source);
            var linked = new LinkedHashSet<>(source);
            var sorted = new TreeSet<>(source);
            System.out.println(hashed.size());
            System.out.println(hashed.contains("A"));
            System.out.println(linked);
            System.out.println(sorted);
        }
    }
    

    The example checks HashSet membership without assuming its printed order. Both ordered outputs are guaranteed by the selected implementations.

  8. Which methods must custom elements supply for hash sets?

    Answer: They must have compatible equals and hashCode behavior. Object inheritance is already valid for identity-based elements. If custom value equality is needed, normally override both methods, not just hashCode. Keep equality-relevant state unchanged while an element is in the set, or remove it before changing that state and then reinsert it.

  9. How do TreeSet and TreeMap differ?

    Answer: TreeSet stores unique elements and implements NavigableSet. TreeMap stores key/value mappings and implements NavigableMap; it sorts keys rather than values. Both support comparison-based navigation such as lower, floor, ceiling, and higher. A map value need not be comparable.

  10. Do all maps use equals() to recognize keys?

    Answer: The ordinary Map contract describes equality-based keys, and HashMap uses hashing plus equality. TreeMap determines whether keys occupy the same position by natural ordering or a comparator returning zero. IdentityHashMap deliberately uses reference identity and documents that it departs from ordinary Map equality semantics.

    For TreeMap to follow the general equality-based Map contract, its ordering should be consistent with equals. Do not assume that every implementation calls key.equals in the same way.

Java SE 25 references: LinkedList, ArrayList, ArrayDeque, HashSet, LinkedHashSet, TreeMap, IdentityHashMap.

SEMrush Software