1

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
}
shadowmanwkp
  • 124
  • 9
user1803704
  • 27
  • 1
  • 1
  • 4

5 Answers5

2
  • 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]) {
Jaydeep Rajput
  • 3,605
  • 17
  • 35
1
if(cakes.get(0).compareTo(cakes.get(1)) > 0) {
    System.out.println("The first cake tastes better than the second");
}
freddy.smith
  • 451
  • 4
  • 9
0

You shoud use if (cakes[0].compareTo( cakes[1]))>0) instead

BlackJoker
  • 3,099
  • 2
  • 20
  • 27
  • Thank you, this solution worked! However, I was under the impression that the '<' operator should work when a compareTo method is defined? When trying to use '<', I get: **The operator < is undefined for the argument type(s) oving9.SokobanResult, oving9.SokobanResult** even though Comparable is implemented in oving9.SokobanResult. – user1803704 Apr 10 '13 at 09:45
0

use the following:

if (cakes.get(0).compareTo(cakes.get(1)) > 0) {
    System.out.println("The first cake tastes better than the second");
}

and read the Comparable documentation

Simulant
  • 19,190
  • 8
  • 63
  • 98
0

if (cakes[0] > cakes[1])...

Is there not a problem here? As people have said, you should use if(cakes[0].compareTo(cakes[1]) > 0) Well I would say that BUT you're using an ArrayList. Can you really get elements by typing listname[elementnumber]? I thought you have to use listname.get(elementnumber).

The Ice Mage
  • 445
  • 1
  • 7
  • 17