Help with an Java exam question
I have an exam using eclipse tomorrow and this is the only question I'm stuck on and just trying to see if I could get any help. Here's the question:
---------------------------------------------------------------------------------------------
"Read the whole question before beginning. You will need both Comparable and Comparator."
A Boat has a name, integer of masts, and double weight. The List fleet is an ArrayList of Boat objects. Boats are usually sorted by name, but in this case you want to be able to do two or more orderings, by number of masts, and by weight.
A) Write the Boat class so that it can be sorted easily by name.
B) Write two or more classes that will allow you to perform the other two sorts. (Hint: the code to sort by number of masts can be much shorter than the weight code.)
C) Show the two lines of code in main() that will sort fleet by name, then by weight.
----------------------------------------------------------------------------------------
All I have is:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Boat implements Comparator<Integer> {
private String name;
private int masts;
private double weight;
public Boat(String name, int masts, double weight){
this.name = name;
this.masts = masts;
this.weight = weight;
}
Re: Help with an Java exam question
Boat should implement Comparable<Boat> not Comparator<Integer>. Then try to give it the only method that Comparable requires it to have, compareTo(...). There are many examples of this to be found here and elsewhere.