Hi! I have a problem with compareTo method.
"Be sure that compareTo method returns different values for different objects".
I've already checked in main method it - and I see that compareTo method returns different values for different objects.
So what does codegym wants from me?
Thanks in advance!
package com.codegym.task.task17.task1714;
/*
Comparable
*/
import java.util.ArrayList;
import java.util.Comparator;
public class Beach implements Comparable<Beach> {
private String name;
private float distance;
private int quality;
public Beach(String name, float distance, int quality) {
this.name = name;
this.distance = distance;
this.quality = quality;
}
public synchronized String getName() {
return name;
}
public synchronized void setName(String name) {
this.name = name;
}
public synchronized float getDistance() {
return distance;
}
public synchronized void setDistance(float distance) {
this.distance = distance;
}
public synchronized int getQuality() {
return quality;
}
public synchronized void setQuality(int quality) {
this.quality = quality;
}
public static void main(String[] args) {
Beach beach1 = new Beach("Ocean", 2.5536f, 5);
Beach beach2 = new Beach("Mary", 5.43f, 3);
Beach beach3 = new Beach("Nice", 3.56f, 2);
int who = beach1.compareTo(beach2);
int who2 = beach2.compareTo(beach1);
int who3 = beach1.compareTo(beach1);
System.out.println(who);
System.out.println(who2);
System.out.println(who3);
System.out.println(beach3.compareTo(beach1));
System.out.println(beach2.compareTo(beach3));
}
@Override
public synchronized int compareTo(Beach beach) {
// if (this.quality == beach.quality) {
// return 0;
// } else if (this.quality > beach.quality) {
// return 1;
// } else {
// return -1;
// }
return Comparator.comparing(Beach::getDistance)
.thenComparing(Beach::getQuality)
.compare(this, beach);
}
}
//Implement the Comparable<Beach> interface in the Beach class. Beaches will be used by threads, so you need to ensure that all the methods are synchronized.
//Implement the compareTo method so that when two beaches are compared the method returns a positive number if the first beach is better
//or a negative number if the second beach is better. The magnitude of the number indicates how much better the beach is.
//
//
//Requirements:
//1. The Beach class must have three fields: String name, float distance, int quality.
//2. The Beach class should implement the Comparable<Beach> interface.
//3. The Beach class's compareTo method should at least account for beach quality and distance.
//4. All of the Beach class's methods, except for the main method, must be synchronized.