Java Questions 110 -120  «Prev  Next»


Comparable | Comparator Interface Questions (120)

  1. What is the difference between the Comparable and Comparator interface?

    Answer:
    A class that implements the Comparable interface has the compareTo method.A class that implements the Comparator interface use the "compare" method.

  2. Which package do you use to sort arrays?

    Answer:
    You use the java.util.Arrays class to sort arrays.

  3. Which similarity exists between arrays and objects?

    Answer: Sorting arrays of objects is just like sorting collections of objects.

  4. What type of method is the sort() method?

    Answer:
    Remember that the sort() methods for both the Collections class and the Arrays class are static methods.

  5. What must be true about the elements that you want to sort?

    Answer:
    Whenever you want to sort an array or a collection, the element inside must all be mutually comparable.

  6. How should one understand the concept of mutually comparable?

    Answer:
    In general, objects of different types should be considered NOT mutually comparable,

  7. The binarySearch() method uses negative numbers to indicate insertion points.

    Answer:
    The insertion point is the place in the collection/array where the element would be inserted to keep the collection/array properly sorted. Whenever you want to sort an array or a collection, the elements inside must all be mutually comparable.

  8. What is the relationship between sorting and searching?

    Answer:
    If the collection/array you want to search was sorted in natural order, it must be searched in natural order.

  9. When should you use sets?

    Answer:
    Sets are used when you do not want duplicates in your collection.
  10. why hashmap is faster than hashset?

    Answer:
    1. HashMap is faster than hashset because the values are associated to unique key
    2. In HashSet, member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different. In HashMap, hashcode value is calculated using key object.

    3. In ash map hashcode value is calculated using key object Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different.