I'm having trouble comparing objects of another class
, how should I proceed?
I made a tasty example, hopefully the code should be self-explanatory.
cake.java:
public class Cake implements Comparable<Cake> {
private final int tastyness;
public Cake(tastyness) {
this.tastyness = tastyness;
}
public int compareTo(Cake other) {
return this.tastyness - other.tastyness;
}
}
makeBestDinner.java:
public class makeBestDinner {
List<Cake> cakes = new ArrayList<cake>();
// Make a whole lot of cakes here
if (cakes[0] > cakes[1]) {
System.out.println("The first cake tastes better than the second");
}
// Do the same for beverages
}
if (cakes[0] > cakes[1]) {
instead, you should
if (cakes.get(0).compareTo(cakes.get(1)) > 0) {
list.get(index)
notlist[index]
So following code will not work.
List<Cake> cakes = new ArrayList<cake>();
// Make a whole lot of cakes here
if (cakes[0] > cakes[1]) {