will such questions ( implementing comparator... using compare() etc come for the exam?)
choose: Compilation succeeds, compare() throws ClassCastException Compilation succeeds, the output is 0 1 2 3 Compilation succeeds, the output is 1 2 3 Compile time error, the compare() method does not have the correct signature Compile Time error, compareTo method from the Comparator interface has not been implemented.
Solution provided: Answer 3 is correct. The compilation succeeds and the output will be in ascending order (e.g.: 1 2 3). The class Car is a Comparator but at the same time also a business object that contains the total of wheels for the car.
At line 20 the TreeSet is created, the TreeSet of the constructor takes in the Car() Comparator, this constructor creates a new empty set sorted according to the Car criteria. All elements must be mutually comparable by the car.compare(Object o1, Object o2) method. The Car object used to create the TreeSet does not belong to the set.
The cars are sorted by the total amount of wheels. 3 new objects are created and added to a list. When the TreeSet start sorting it will call the compare method and it compares the total of wheels. It uses the Integer compareTo method.