1Z0-771 study materials
1Z0-771 study resources

1Z0-771: Generics and Collections

1Z0-771 · Work through your exam, one topic at a time.

All guide sections

Generics and Collections

Domain 4 tests type erasure, wildcard variance, and collection contracts: which implementation to choose, what happens with duplicate keys, and when iteration throws ConcurrentModificationException.

Generics

  • Generics exist only at compile time; erasure removes type arguments, so List<String> and List<Integer> share one runtime class. You cannot use primitives, test instanceof List<String>, call new T(), or create a generic array.
  • Bounds: <T extends Number & Comparable<T>> - at most one class, listed first, then interfaces.
  • Wildcards follow PECS: List<? extends Number> is a producer (you may read Number, but adding is illegal); List<? super Integer> is a consumer (you may add Integer, but reading yields only Object).
  • Generic methods declare their own parameter before the return type: static <T> T pick(List<T> list).

Collections

  • List is ordered with duplicates; Set rejects duplicates by equals/hashCode; Map keys are unique.
  • ArrayList is the general-purpose list; HashSet/HashMap are unordered with O(1) average access; TreeSet/TreeMap sort by Comparable or a Comparator in O(log n).
  • List.of, Set.of, Map.of return immutable collections that reject null and throw UnsupportedOperationException on mutation.
  • HashMap allows one null key; Hashtable and ConcurrentHashMap do not.
  • Mutating a collection while iterating with anything other than Iterator.remove() triggers ConcurrentModificationException from fail-fast iterators.

Worked example

List<? extends Number> in = List.of(1, 2.0);
Number n = in.get(0);   // fine
in.add(3);              // compile error: unknown subtype of Number
List<? super Integer> out = new ArrayList<Number>();
out.add(3);             // fine
Integer i = out.get(0); // compile error: only Object is guaranteed

Traps

  • Comparator must return negative, zero or positive; an inconsistent comparator corrupts a TreeSet.
  • A mutable key whose hashCode changes becomes unreachable in a HashMap.
  • Arrays.asList returns a fixed-size list backed by the original array.