Java Questions 111 -120  «Prev  Next»


Java SE 25: Maps, Queues, and Priority Ordering

Review HashMap null support, synchronized legacy classes, access order, TreeMap comparisons, and correct PriorityQueue traversal in Java SE 25.

  1. What keys and values can HashMap store?

    Answer: HashMap<K,V> stores reference values compatible with K and V, including one null key and any number of mappings with null values. Primitive values are boxed when used with wrapper type arguments. A Map<String,Object> can hold values of different reference types, while a Map<String,String> cannot hold an Integer.

    Keys are unique according to their equality contract; values may repeat. A get result of null does not by itself distinguish a missing key from a key explicitly mapped to null. Use containsKey for that distinction.

    Example HashMap value types: String, Integer, null, and List of String
    Example value types for a Map<String,Object>. Each repeated "Key" label represents a distinct key; reusing an equal key replaces its mapping.
  2. What does synchronized mean for Vector and Hashtable?

    Answer: Many of their individual operations acquire the object monitor, coordinating callers that use the same locking discipline. This does not automatically make a multi-call sequence atomic, nor does it make arbitrary work on retrieved elements thread-safe.

    For example, checking for a key and then inserting it can require one coordinated operation or an external lock around both calls. Choose operations such as putIfAbsent with the guarantees of the particular map implementation in mind.

  3. What are the main differences between HashMap and Hashtable?

    Answer: HashMap permits null keys and values and is not synchronized. Hashtable rejects null keys and values and synchronizes its operations. Both are hash-based maps with no iteration-order guarantee. Hashtable is a legacy class; HashMap is part of the framework introduced later.

    For concurrent access, evaluate ConcurrentHashMap or a properly synchronized wrapper. Fail-fast iterators do not guarantee detection of every concurrent modification, and the exception can also arise from incorrect changes within a single thread.

  4. How does null handling distinguish HashMap from Hashtable?

    Answer: HashMap accepts a null key and null values. Hashtable rejects either with NullPointerException. The null key still identifies only one mapping: another put with a null key replaces its value. ConcurrentHashMap also rejects null, so it is not a drop-in replacement when null mappings are part of the design.

  5. What is distinctive about LinkedHashMap?

    Answer: It has a defined encounter order, normally insertion order. The constructor new LinkedHashMap<K,V>(16, 0.75f, true) enables access order, from least recently accessed to most recently accessed. In Java SE 25, SequencedMap operations expose entries at both ends and reversed views.

    Which operations count as accesses is documented by LinkedHashMap; for example, a successful get counts, while merely traversing an entry view does not. Access order alone does not impose a capacity limit or automatic eviction.

  6. What is a TreeMap?

    Answer: TreeMap is a NavigableMap backed by a red-black tree. It maintains keys in natural or comparator order, with logarithmic containsKey, get, put, and remove operations. It can retrieve nearest keys and range views. Values need not be ordered, and null values are allowed.

    Natural-order TreeMap does not accept null keys. A custom comparator may support null keys if it defines their position. Keep key comparison state stable while stored.

  7. How do you define a custom order for TreeSet or TreeMap?

    Answer: Pass a Comparator to the constructor. TreeSet compares elements; TreeMap compares keys. Implementing Comparable on the element or key type defines its natural ordering instead. For example, new TreeSet<String>(Comparator.reverseOrder()) reverses String natural order.

    If comparison returns zero, the structure treats the two elements or keys as equivalent for membership. A comparator that ignores important identity fields can therefore collapse distinct values.

  8. What is the purpose of Queue?

    Answer: Queue holds elements for processing under an implementation-defined ordering. FIFO queues are common, but PriorityQueue uses priority ordering. offer attempts insertion, poll retrieves and removes the head or returns null if empty, and peek examines the head or returns null.

    The corresponding add, remove, and element forms signal certain failures through exceptions. Capacity restrictions and concurrency behavior come from the implementation; the Queue interface does not promise that all queues are FIFO or blocking.

  9. How can LinkedList be used as a queue in Java SE 25?

    Answer: It implements Deque, which extends Queue. Declare Queue<String> jobs = new LinkedList<>(), append with offer, and remove from the head with poll for FIFO behavior. This capability has existed for many Java releases; it is not a new Java 25 enhancement.

  10. Does PriorityQueue provide a sorted traversal?

    Answer: No. It keeps the least element according to its ordering at the head, but iteration and toString do not promise sorted order. Repeated poll calls produce priority order if the queue is not otherwise changed and comparison state stays stable. Equal-priority ties are arbitrary.

    PriorityQueue permits duplicates, rejects null, and is not synchronized. Use a reverse comparator when the largest value should come out first. Offer and poll are logarithmic; peek is constant time.

    import java.util.Comparator;
    import java.util.List;
    import java.util.PriorityQueue;
    
    public class PriorityRemoval {
        public static void main(String[] args) {
            PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder());
            queue.addAll(List.of(30, 10, 20));
            while (!queue.isEmpty()) {
                System.out.println(queue.poll());
            }
        }
    }
    
    Example min-heap with 10 at the root, followed by 20, 30, and 40
    One valid min-heap example. Its pictured array happens to be sorted; a heap does not require a globally sorted array, and PriorityQueue iteration is not sorted.

Java SE 25 references: HashMap, Hashtable, LinkedHashMap, TreeMap, Queue, PriorityQueue, ConcurrentHashMap.

SEMrush Software