Java Questions 110 -120  «Prev  Next»


Java SE 25 Comparable Interface, Lists, ArrayList, and Collection Ordering

Java collections are designed around interfaces, implementation classes, ordering rules, and type-safe generics. In Java SE 25, the Comparable interface still defines a class's natural ordering, while List, Set, ArrayList, LinkedList, and legacy classes such as Vector each have different ordering and performance characteristics. This interview review explains those differences using current Java terminology.

  1. What is the purpose of the Comparable interface?
    Answer:
    The Comparable<T> interface defines the natural ordering for objects of a class. A class that implements Comparable provides a compareTo() method that determines whether the current object is less than, equal to, or greater than another object of the same compatible type.

    Natural ordering is used by sorting operations such as Collections.sort(), List.sort(), and sorted collections such as TreeSet and TreeMap.
    public record Employee(int id, String name) implements Comparable<Employee> {
        @Override
        public int compareTo(Employee other) {
            return Integer.compare(this.id, other.id);
        }
    }

    In this example, Employee objects have a natural order based on id. If a different order is needed, such as sorting by name, use a Comparator.

  2. Why do some collection data structures not maintain insertion order?
    Answer:
    Different collection implementations are optimized for different behavior. Some preserve insertion order, some sort elements, and some make no promise about iteration order.
    1. List implementations such as ArrayList and LinkedList preserve positional order. Elements are accessed by index.
    2. HashSet is optimized for hash-based lookup and does not guarantee insertion order.
    3. LinkedHashSet preserves insertion order.
    4. TreeSet stores elements according to their natural order or a supplied Comparator.

    Insertion order, sorted order, access order, and index order are different concepts. Choosing the correct collection depends on which kind of ordering the program requires.
  3. What differentiates a List from non-list collections?
    Answer:
    A List is an ordered collection that gives the programmer precise control over where each element is inserted. It supports index-based operations such as get(int index), set(int index, E element), add(int index, E element), and remove(int index).
    import java.util.ArrayList;
    import java.util.List;
    
    List<String> languages = new ArrayList<>();
    languages.add("Java");
    languages.add("Kotlin");
    languages.add(1, "Scala");
    
    System.out.println(languages.get(1));
  4. What are common Java List implementations ordered by?
    Answer:
    Common List implementations are ordered by index position. The programmer controls where elements appear in the list.
    1. ArrayList - array-backed, efficient random access.
    2. LinkedList - node-based list and deque implementation.
    3. Vector - legacy synchronized list implementation.

    In modern Java, ArrayList is usually the default general-purpose list implementation. Vector is retained for compatibility with older Java code, but it is rarely the first choice for new development.
  5. What is the purpose of an ArrayList?
    Answer:
    ArrayList is a resizable-array implementation of the List interface. It preserves element order, supports indexed access, grows as elements are added, and works with generics for compile-time type safety.
    import java.util.ArrayList;
    import java.util.List;
    
    List<String> topics = new ArrayList<>();
    topics.add("Comparable");
    topics.add("ArrayList");
    topics.add("Generics");
    
    System.out.println(topics.get(0));
    System.out.println(topics.size());

    ArrayList is efficient for random access and iteration. Adding or removing elements near the middle or beginning of a large list can be more expensive because later elements may need to be shifted.

  6. When should you choose ArrayList over LinkedList?
    Answer:
    Choose ArrayList when the program needs fast indexed access, compact memory usage, and efficient iteration. It is usually the best default implementation for a general-purpose List.

    Choose LinkedList only when the program benefits from its deque behavior or from frequent insertions and removals through an iterator at known positions. Even then, real performance should be measured, because ArrayList often performs better in typical application code due to better memory locality.
  7. What were the original legacy collection classes?
    Answer:
    Two important early collection classes were:
    1. Vector
    2. Hashtable

    These classes existed before the modern Java Collections Framework was introduced. They remain available for backward compatibility, but modern Java programs usually prefer ArrayList, HashMap, ConcurrentHashMap, or synchronized wrappers from Collections, depending on the requirement.
  8. What is the difference between Vector and ArrayList?
    Answer:
    Vector and ArrayList are both resizable-array list implementations, but Vector synchronizes many of its methods while ArrayList does not. Synchronization can make individual method calls on Vector thread-safe, but it also adds overhead and does not automatically make compound actions safe.

    For new Java SE 25 code, use ArrayList for ordinary list storage. If thread-safe access is required, consider Collections.synchronizedList(), CopyOnWriteArrayList, or another concurrency-oriented collection depending on the access pattern.
  9. Which list classes implement RandomAccess?
    Answer:
    ArrayList and Vector implement the RandomAccess marker interface. This interface indicates that the list supports efficient random access by index. LinkedList does not implement RandomAccess because indexed access requires traversal through nodes.
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.RandomAccess;
    import java.util.Vector;
    
    System.out.println(new ArrayList<String>() instanceof RandomAccess);
    System.out.println(new Vector<String>() instanceof RandomAccess);
    System.out.println(new LinkedList<String>() instanceof RandomAccess);
  10. How can you print all values stored in an ArrayList?
    Answer:
    You can print the values in an ArrayList using an enhanced for loop, a traditional index-based loop, forEach(), or by printing the list directly when the default list format is acceptable.
    import java.util.ArrayList;
    import java.util.List;
    
    List<String> list = new ArrayList<>();
    list.add("Java");
    list.add("Collections");
    list.add("ArrayList");
    
    for (String value : list) {
        System.out.println(value);
    }
    
    list.forEach(System.out::println);
    
    System.out.println(list);

    For lists of custom objects, override toString() in the custom class when the object needs a readable text representation.

These collection topics remain useful in Java SE 25 because they explain the difference between natural ordering, insertion order, index order, and legacy synchronized collection behavior. A Java developer should understand when to use Comparable, when to use Comparator, and why ArrayList is usually preferred over legacy classes such as Vector for new application code.


SEMrush Software