I'm trying to implement Comparable
and compareTo()
, but can't seem to get it to work. I've been trying different methods but I don't really get it. I know I'm supposed to implement the comparable interface, and that I need to create the method compareTo()
before using it (strange for me, coming from python to object-oriented programming).
I would like it to compare the ages of two humans, so I tried writing the code as seen below, but it seems I can't use compareTo(). I'm getting the error message: "This method must return an int type", but as I see it, I am only returning 1, -1 and 0, which are int
?
Also, I know the print-row in the end is wrong. How can I change it so it says for example: "Name1, 25 yrs old, is older than Name2, 21 yrs old". In python I could extract 2 specific values from a list and compare them with some given method; I'm not sure how to do the extraction for 2 different values in Java.
import java.util.ArrayList;
import java.util.Random;
class Human implements Comparable<Human>{
int age;
String name;
public Human (int myAge, String myName) {
name = myName;
age = myAge;
}
public Human() {
this(randomAge(),randomName());
}
public int compareTo(Human o) {
if (this.age > o.age) {
return 1;
}
if (this.age < o.age) {
return -1;
}
if (this.age == o.age) {
return 0;
}
}
protected static int randomAge() {
Random randomGenerator = new Random();
return randomGenerator.nextInt(99);
}
protected static String randomName() {
Random randomGenerator = new Random();
return "Name"+randomGenerator.nextInt(15);
}
public int getAge(){
return age;
}
public String getName() {
return name;
}
public String toString() {
return "\nName: " + name + "\nAge: " + age + " yrs old\n";
}
public static void main (String[] args) {
ArrayList<Human> randomHumans = new ArrayList<Human>();
for (int j=0;j<2;j++) {
Human randomPerson = new Human();
randomHumans.add(randomPerson);
}
System.out.println(insert.something.here);
}
}
So using three if-statements does not work, which is why I could have written an if/else if/else statement instead, but another simpler solution would have been to write this in the compareTo(Human o)
-method;
return this.age - o.age
Then for the print in the end;
int b = randomHumans.get(0).compareTo(randomHumans.get(1));
if (b>0) {
System.out.println(randomHumans.get(0).getName()+", "+randomHumans.get(0).getAge()+" yrs old, is older than "+randomHumans.get(1).getName()+", "+randomHumans.get(1).getAge()+" yrs old.");
}
else if (b<0) {
System.out.println(randomHumans.get(0).getName()+", "+randomHumans.get(0).getAge()+" yrs old, is younger than "+randomHumans.get(1).getName()+", "+randomHumans.get(1).getAge()+" yrs old.");
}
else {
System.out.println(randomHumans.get(0).getName()+", "+randomHumans.get(0).getAge()+" yrs old, is just as old as "+randomHumans.get(1).getName()+", "+randomHumans.get(1).getAge()+" yrs old.");
}