Java Certification Questions 111 -120  «Prev  Next»


Java Queue Questions (122)

  1. How does a PriorityQueue order its elements?

    Answer: In Java, a `PriorityQueue` orders its elements **according to their natural ordering** (defined by the `Comparable` interface) or **by a `Comparator`** provided at queue construction time.
    Ordering Behavior:
    1. Natural Ordering (Default):
      • Elements must implement Comparable<T>.
      • The element with the lowest value (according to compareTo()) is given highest priority and dequeued first.
      • Example: For integers, 1 has higher priority than 5.
      •           PriorityQueue<Integer> pq = new PriorityQueue<>();
                  pq.add(5);
                  pq.add(1);
                  pq.add(3);
                  System.out.println(pq.poll()); // Outputs 1
                
    2. Custom Ordering (Using Comparator):
      • You can specify a custom Comparator when constructing the queue.
      •           PriorityQueue<String> pq = new PriorityQueue<>(Comparator.reverseOrder());
                  pq.add("Apple");
                  pq.add("Banana");
                  pq.add("Cherry");
                  System.out.println(pq.poll()); // Outputs "Cherry"
                

    Key Properties:
      • Heap-based structure: Internally, it uses a binary heap (usually a min-heap by default).
      • Not sorted when iterated: Calling iterator() does not return elements in priority order.
      • Time complexity:
        • Insertion: \(O(\log n)\)
        • Retrieval/removal (poll()): \(O(\log n)\)
        • Peek (peek()): \(O(1)\)
    A diagram showing the heap structure of a PriorityQueue A diagram showing the heap structure of a PriorityQueue
    A PriorityQueue orders its elements using a user-defined priority?


  2. Which interface does a PriorityQueue implement to impose an ordering other than “natural ordering”?

    Answer:
    The Comparator interface.

  3. What does the T[] syntax represent?

    `T[]` Syntax in Java
    In Java, `T[]` represents an **array of elements of type `T`**, where `T` is a **generic type parameter** or a **reference type**. It is **not used for arrays of primitives** unless `T` is explicitly a primitive type (which is rare in generics due to Java's type system restrictions).
    Explanation:
    1. `T` as a Type Parameter (Generic)

      When used in a generic class or method, T[] indicates an array of generic elements:

            public class Box<T> {
              private T[] items;
      
              public void setItems(T[] items) {
                this.items = items;
              }
      
              public T getFirstItem() {
                return items[0];
              }
            }
          

      Here:

      • T can be any reference type like String, Integer, MyClass, etc.
      • You cannot create new T[] directly due to type erasure. You often need to pass in an array or use Array.newInstance() via reflection.
    2. `T[]` as an Array of Non-Primitives

      You cannot use T[] with primitive types like int, char, double directly in a generic context:


    Examples:
    public  void printArray(T[] array) {
        for (T element : array) {
            System.out.println(element);
        }
    }
    

    Valid call:
    String[] strings = {"Java", "GPT"};
    printArray(strings); // Works
    

    Invalid call (will not compile):
    int[] nums = {1, 2, 3};
    printArray(nums); // Error: incompatible types
    

    Summary Table
    Syntax Meaning Works with Primitives?
    T[] Array of generic or reference type T ❌ Not for primitives
    String[] Array of String objects
    int[] Array of primitives ✅ but not with generics
    Answer: This syntax represents an array that is not an array of primitives.

  4. Can the Iterator interface be used with the Map interface?

    Answer: No. The Iterator interface will get an Iterator for a List or a Set.

  5. What are the relative positions of uppercase characters, lowercase characters, and spaces in a natural ordering?

    Answer: Spaces sort before characters and uppercase letters sort before lowercase characters.

  6. What is the difference between NavigableSet and NavigableMap interfaces?

    Answer:
    NavigableSet<E> inherits from Iterable<T> .
    NavigableMap<K,V> inherits from Map<K,V> .

  7. Why were Generics added to the Java language?

    Answer: Collections are the overwhelming reason and motivation for adding generics to the language.

  8. Can you integrate Java 5 and Java 6 generic code with legacy non-generic code?

    Answer: Yes, but most of the errors will occur at run time

  9. How many ways can we track client and what are they?

    Answer:
    The servlet API provides two ways to track client state and they are:
    1. Using Session tracking and
    2. Using Cookies.

  10. What is a characteristic of a non-generic collection?

    Answer:
    A non-generic collection can hold any kind of object. A non-generic collection is quite happy to hold anything that is NOT a primitive.