Enrol to start learning
Reading is open to everyone. Enrolling is free, and it is what unlocks the audio lessons, practice tests and progress tracking.
15.8.2. Comparator Interface
This section
Practice test
12 questions on this section. Wrong answers show you what to read again.
Sign up to take itWhole chapter
Revision test
Mixed questions from across the chapter. Your answers get marked.
Sign up to take itQuick
Flashcard drill
4 cards from this lesson. Good the night before a test.
Try these first
- 1.
What is the purpose of the Comparator interface in Java?
Hint
Think about when you'd need to sort items differently.
- 2.
What method do you need to implement in a Comparator?
Hint
What are the two objects you compare?
- 3.
What does the Comparator interface allow you to do?
- A. Sort objects naturally
- B. Define custom ordering for objects
- C. Force comparison between two objects
- D. Merge multiple lists
Hint
Think about what flexibility you need beyond natural ordering.
- 4.
True or False: A Comparator can only sort objects in increasing order.
- True
- False
Hint
Consider how you could reverse the sorting order.
- 5.
Create a Comparator for a class that represents products in a store. The Comparator should first compare products by price, and then by name if prices are the same.
Hint
Think about the significance of each attribute when comparing.
- 6.
Imagine you have a data structure that needs to sort student records by GPA, and if two students have the same GPA, by last names. Design your solution using the Comparator interface.
Hint
What condition checks will you need?
Exercises
Total Questions
2
Estimated Time
4 min
Passing Score
70%
Instructions
- Read each question carefully
- You can use hints if you need help
- Complete all questions before submitting
4 more questions available
Enrol freeQuiz
Total Questions
2
Estimated Time
4 min
Passing Score
70%
Instructions
- Read each question carefully
- You can use hints if you need help
- Complete all questions before submitting
2 more questions available
Enrol freeChallenge Problems
Total Questions
2
Estimated Time
4 min
Passing Score
70%
Instructions
- Read each question carefully
- You can use hints if you need help
- Complete all questions before submitting