Witam. Czytałem informacje dot. metody compareTo w javie i zrozumiałem że w domyśle ma ona zwracać wartości -1/0/1. Czy może mi ktoś pomóc napisać metodę która będzie porównywała ceny w mojej klasie i zwracała własnie wartości -1/0/1? Oto mój kod
public abstract class Vehicle implements UseFuel,HasWheels, Comparable<Vehicle>
{
String brand;
int weigth;
int price;
public Vehicle(String brand, int weight, int price)
{
this.brand = brand;
this.weigth = weight;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getWeigth() {
return weigth;
}
public void setWeigth(int weigth) {
this.weigth = weigth;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String toString() {
return "Vehicle brand=" + brand + ", weigth=" + weigth + ", price=" + price + "";
}
/*public int compareTo(Vehicle other ) {
return this.price.compareTo(other.getPrice());
}*/
public int compareTo(Vehicle other ) {
if (this.price > other.price) return 1;
else if (this.price == other.price) return 0;
else
return -1;
}
public boolean isBrandEqual(Vehicle x, Vehicle y)//porownywanie marki
{
if (x.brand == y.brand) return true;
else
return false;
}
}
Niby próbowałem to już sam napisać, druga metoda compareTo(ta która nie jest wykomentowana) działa dobrze, bo zwraca 1,-1 oraz 0, ale to tylko dlatego że napisałęm tam return -1, a domyślam się że ona powinna domyślnie sama zwracać takie wartośći?
/*public int compareTo(Vehicle other ) {
return this.price.compareTo(other.getPrice());
}*/
public int compareTo(Vehicle other ) {
if (this.price > other.price) return 1;
else if (this.price == other.price) return 0;
else
return -1;
}