Search code examples
javacomparable

Compare objects of other class


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
}

Solution

    • Java does not support operator overloading hence following will not work.
      if (cakes[0] > cakes[1]) {
    

    instead, you should

    if (cakes.get(0).compareTo(cakes.get(1)) > 0) {
    
    • Also to get elements from list we need to call list.get(index) not

    list[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]) {