Generics and Collections Flashcards
7 cards from real OCP practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Generics and Collections flashcards as text
Which interface must a class implement so its instances can be stored in a TreeSet without a Comparator?
Answer: java.lang.Comparable
TreeSet requires elements to implement Comparable (specifically compareTo()) for natural ordering unless an explicit Comparator is supplied.
What is the effect of the following code? ```java List src = Arrays.asList(1, 2, 3); List dst = Arrays.asList(0, 0, 0); Collections.copy(dst, src); System.out.println(dst); ```
Answer: [1, 2, 3]
Collections.copy() copies src into dst in-place; Arrays.asList returns a fixed-size but mutable list, so set() works and dst becomes [1, 2, 3].
Which of the following correctly compiles and creates a Map entry stream in Java 8+?
Answer: map.entrySet().stream()
Map does not extend Iterable or Stream directly; you must call entrySet().stream() to stream the Map.Entry objects.
What is printed by the following snippet? ```java Map m = new HashMap<>(); m.put("a", 1); System.out.println(m.getOrDefault("b", 99)); ```
Answer: 99
getOrDefault() returns the mapped value if the key exists, or the provided default (99) if the key is absent.
Which statement about generic type bounds is TRUE?
Answer: `` is valid
A type parameter can extend one class and multiple interfaces using `&` as separator; `` is valid syntax.
What is the purpose of Collections.frequency(Collection c, Object o)?
Answer: Returns the number of times o appears in c
Collections.frequency() counts and returns the number of elements in the collection that are equal to the specified object.
Which of the following statements about EnumSet is correct?
Answer: EnumSet is implemented as a bit vector and only holds enum constants
EnumSet is internally represented as a bit vector (RegularEnumSet or JumboEnumSet), making it extremely compact and fast for enum constants.