Collections (List/Set/Map) Questions with Answers

24 practice questions on Collections (List/Set/Map) (Core Java) with answers and step-by-step solutions. Try 10 samples below, then practise all 24 free in the AptiNest app.

Sample questions

Question 1Easy

What is the output?

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Queue<Integer> q = new LinkedList<>();
        q.offer(4);
        q.offer(9);
        q.offer(1);
        System.out.println(q.poll() + " " + q.peek());
    }
}
  1. 4 9
  2. 4 4
  3. 1 9
  4. 9 1

Answer: A. 4 9

Explanation

A Queue is FIFO: poll removes the first inserted element 4, and peek shows the next one, 9.

Step-by-step solution

  1. A LinkedList used as a Queue is first in, first out.
  2. poll() removes and returns the first element, 4.
  3. peek() shows the new head, 9.
  4. Output is 4 9 (option A).

Why the other options are wrong

  • B. Peek shows 9, the next element, not 4 again.
  • C. 1 was added last, so it is not the first to leave.
  • D. 9 is second in the queue, so it does not leave first.

Tip: Queue offer adds at the tail, poll removes from the head, and peek shows the head without removing it.

Question 2Easy

Which collection class is best when you need key-value pairs kept sorted by key?

  1. HashMap
  2. LinkedHashMap
  3. TreeMap
  4. ArrayList

Answer: C. TreeMap

Explanation

TreeMap is a red-black tree that keeps keys in sorted order with O(log n) operations; HashMap has no order and LinkedHashMap keeps insertion order.

Step-by-step solution

  1. HashMap has no defined order and LinkedHashMap keeps insertion order.
  2. TreeMap keeps its keys sorted by key using a red-black tree.
  3. Sorted key-value pairs need TreeMap, which is index 2.

Why the other options are wrong

  • A. HashMap stores keys in no particular order.
  • B. LinkedHashMap keeps insertion order, not sorted order.
  • D. ArrayList holds plain values, not key-value pairs.

Tip: Sorted keys: TreeMap. Insertion order: LinkedHashMap. No order needed: HashMap.

Question 3Easy

What is the output?

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> m = new TreeMap<>();
        m.put("banana", 2);
        m.put("apple", 5);
        m.put("cherry", 1);
        System.out.println(m.keySet() + " " + m.get("apple"));
    }
}
  1. [banana, apple, cherry] 5
  2. [apple, banana, cherry] 5
  3. [cherry, banana, apple] 5
  4. [apple, banana, cherry] 2

Answer: B. [apple, banana, cherry] 5

Explanation

TreeMap sorts keys in natural order, and get("apple") returns 5.

Step-by-step solution

  1. TreeMap stores keys in sorted order based on their natural ordering.
  2. Natural order of strings is alphabetical, so keys are ordered as apple, banana, cherry.
  3. m.keySet() returns [apple, banana, cherry].
  4. m.get("apple") returns 5 from the map.
  5. Final output is [apple, banana, cherry] 5.
  6. Answer: [apple, banana, cherry] 5.

Why the other options are wrong

  • A. That is insertion order; TreeMap sorts keys alphabetically, so apple comes first.
  • C. That is reverse alphabetical order; TreeMap sorts keys ascending, so apple comes first.
  • D. The key order is right, but apple was stored with 5, so get returns 5, not 2.

Tip: Remember TreeMap orders keys alphabetically by default.

Question 4Easy

What is the output?

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> m = new LinkedHashMap<>();
        m.put("c", 3);
        m.put("a", 1);
        m.put("b", 2);
        m.put("c", 30);
        System.out.println(m);
    }
}
  1. {a=1, b=2, c=3}
  2. {a=1, b=2, c=30}
  3. {c=3, a=1, b=2, c=30}
  4. {c=30, a=1, b=2}

Answer: D. {c=30, a=1, b=2}

Explanation

LinkedHashMap keeps insertion order, and re-putting an existing key replaces its value without moving it.

Step-by-step solution

  1. LinkedHashMap keeps keys in first-insertion order: c, a, b.
  2. put('c', 30) replaces the value of c but does not move c.
  3. The map prints in order c, a, b with c=30.
  4. Output is {c=30, a=1, b=2} (option D).

Why the other options are wrong

  • A. C's value was replaced with 30, so c=3 is not printed.
  • B. C's value is 30, but c stays first, so a is not printed first.
  • C. A map holds each key only once, so c appears once.

Tip: A LinkedHashMap keeps the original insertion position when a key's value is replaced.

Question 5Medium

What is the output?

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
        for (Integer x : list) {
            if (x == 2) list.remove(x);
        }
        System.out.println(list);
    }
}
  1. ConcurrentModificationException is thrown
  2. [1, 3, 4]
  3. [1, 2, 3, 4]
  4. [1, 3]

Answer: A. ConcurrentModificationException is thrown

Explanation

Structurally modifying an ArrayList while iterating it with for-each makes the iterator fail fast on its next call to next().

Step-by-step solution

  1. The loop iterates over list using for-each.
  2. Inside loop, x == 2 is true for element 2.
  3. list.remove(x) modifies the list during iteration.
  4. This causes ConcurrentModificationException.
  5. Final output is ConcurrentModificationException is thrown.

Why the other options are wrong

  • B. Removing an element during for-each throws before printing, so the list never shows [1, 3, 4].
  • C. The list is changed, because remove(x) runs when x equals 2, but the loop then fails.
  • D. Only the value 2 matches x == 2, and the loop throws before any output, so no list is printed.

Tip: Never modify a list during iteration using for-each loop.

Question 6Medium

What is the output?

import java.util.*;

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
        pq.addAll(List.of(3, 8, 1, 5));
        System.out.print(pq.poll() + " ");
        System.out.println(pq.poll());
    }
}
  1. 1 3
  2. 8 1
  3. 3 8
  4. 8 5

Answer: D. 8 5

Explanation

With reverseOrder the priority queue is a max-heap, so poll returns 8 then 5.

Step-by-step solution

  1. reverseOrder() makes the PriorityQueue a max-heap.
  2. AddAll stores 3, 8, 1, 5, and the first poll returns the largest, 8.
  3. The second poll returns the next largest, 5.
  4. Output is 8 5 (option D).

Why the other options are wrong

  • A. 1 is the smallest, so a max-heap returns it last.
  • B. 1 is the smallest; the second poll returns 5, not 1.
  • C. 3 is not the largest; 8 comes out first.

Tip: A PriorityQueue returns the element that the comparator ranks first; reverseOrder ranks the largest first.

Question 7Medium

What is the main difference between ArrayList and LinkedList?

  1. ArrayList cannot hold duplicates but LinkedList can
  2. LinkedList stores elements in sorted order
  3. LinkedList is synchronized and ArrayList is not
  4. ArrayList gives O(1) random access by index, while LinkedList needs O(n) to reach an index but inserts/removes at known nodes cheaply

Answer: D. ArrayList gives O(1) random access by index, while LinkedList needs O(n) to reach an index but inserts/removes at known nodes cheaply

Explanation

ArrayList is backed by a resizable array; LinkedList is a doubly linked list. Neither is synchronized, both allow duplicates and keep insertion order.

Step-by-step solution

  1. ArrayList uses an array for storage, allowing O(1) access by index.
  2. LinkedList uses nodes with pointers, requiring O(n) to reach an index.
  3. ArrayList inserts/removes at the end efficiently but is slow at middle.
  4. LinkedList inserts/removes at known nodes quickly but accessing by index is slow.
  5. Correct answer matches these time complexity differences.

Why the other options are wrong

  • A. Both List types allow duplicate elements; only Set types reject duplicates.
  • B. Neither list sorts elements; both keep insertion order unless you sort them yourself.
  • C. Neither is synchronized; both need external synchronization or a wrapper for thread safety.

Tip: Remember: ArrayList = array, fast access; LinkedList = nodes, fast inserts/removes.

Question 8Medium

What is the output? Point overrides neither equals() nor hashCode().

import java.util.*;

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

public class Main {
    public static void main(String[] args) {
        Set<Point> s = new HashSet<>();
        s.add(new Point(1, 2));
        s.add(new Point(1, 2));
        System.out.println(s.size());
    }
}
  1. 1
  2. 0
  3. Compilation error
  4. 2

Answer: D. 2

Explanation

Without overriding equals() and hashCode(), two distinct objects are never equal (identity comparison), so the HashSet keeps both.

Step-by-step solution

  1. Point does not override equals() or hashCode(), so equality is identity.
  2. The two new Point(1, 2) calls create two different objects.
  3. HashSet keeps both, because the objects are not equal.
  4. size() is 2, which is option D.

Why the other options are wrong

  • A. The two objects are distinct, so the set holds both and size is not 1.
  • B. A set holding two distinct objects has size 2, not 0.
  • C. The code compiles and runs.

Tip: To use objects as set or map keys by value, override equals() and hashCode() together.

Question 9Hard

Which statement about a Comparator used by a TreeMap is correct?

  1. Keys for which compare() returns 0 are treated as the same key, even if equals() returns false
  2. TreeMap ignores the comparator for String keys
  3. A comparator that returns 0 throws IllegalArgumentException
  4. TreeMap uses equals() to detect duplicate keys and compare() only to order them

Answer: A. Keys for which compare() returns 0 are treated as the same key, even if equals() returns false

Explanation

Sorted maps and sets rely only on compareTo/compare for equality; that is why the comparator should be consistent with equals.

Step-by-step solution

  1. A TreeMap with a Comparator uses compare() to order its keys.
  2. If compare() returns 0, the two keys are treated as the same key, whatever equals() says.
  3. So TreeMap uses the comparator both for ordering and for deciding duplicate keys.
  4. So option A correctly describes TreeMap's behaviour.

Why the other options are wrong

  • B. TreeMap uses the comparator for every key, including String keys, so it is not ignored.
  • C. Returning 0 means the keys are equal, so TreeMap treats them as one key; no exception is thrown.
  • D. TreeMap uses compare() to detect duplicates, not equals(); a 0 from compare() means duplicate.

Tip: Remember: Comparator defines equality in TreeMap, not equals().

Question 10Hard

What is the output? Key overrides hashCode() but not equals().

import java.util.*;

class Key {
    int id;
    Key(int id) { this.id = id; }
    @Override public int hashCode() { return id; }
}

public class Main {
    public static void main(String[] args) {
        Map<Key, String> m = new HashMap<>();
        m.put(new Key(7), "seven");
        System.out.println(m.containsKey(new Key(7)) + " " + (new Key(7).hashCode() == new Key(7).hashCode()));
    }
}
  1. false false
  2. false true
  3. true false
  4. true true

Answer: B. false true

Explanation

The equal hash codes lead HashMap to the right bucket, but the inherited equals() compares identity, so the new Key(7) does not match the stored one. equals and hashCode must be overridden together.

Step-by-step solution

  1. Key overrides hashCode() only, so equals() still compares identity.
  2. containsKey(new Key(7)) finds the bucket for hash 7, but the new object is not identical to the stored key, so it returns false.
  3. New Key(7).hashCode() is 7 both times, so the second check is true.
  4. Output is false true (option B).

Why the other options are wrong

  • A. The hash codes match, so the second check is true, not false.
  • C. ContainsKey is false, because equals is not overridden.
  • D. ContainsKey is false, because the new key is not equal to the stored key.

Tip: Overriding only one of equals() and hashCode() breaks HashMap and HashSet lookups.

Practise all 24 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Core Java topics · All topics