Должно отсортировать по цене, но пишет вроде бы то, что обычно пишет, если Comparable не использовать, если я правильно понял. Повторял за примером с сайта и скорее всего чего-то недопонял, вот ссылка, если понадобится: https://vertex-academy.com/tutorials/ru/interfejsy-comparable-comparator-java/
1 файл:
public interface Comparable<T>{
public int compareTo(T o);
}
2 файл:
public class Guns implements Comparable<Guns>{
float weight;
long price;
String manifacturerName;
boolean hasOwner;
public Guns(float weight, long price, String manifacturerName, boolean hasOwner){
this.weight = weight;
this.price = price;
this.manifacturerName = manifacturerName;
this.hasOwner = hasOwner;
}
@Override
public String toString(){
final StringBuffer sb = new StringBuffer("Guns{");
sb.append("weight=").append(weight);
sb.append(", price=").append(price);
sb.append(", manifacturerNname=").append(manifacturerName).append('\'');
sb.append(", hasOwner=").append(hasOwner);
sb.append('}');
return sb.toString();
}
public int compareTo(Guns anotherGun) {
if(this.price == anotherGun.price) {
return 0;
} else if(this.price > anotherGun.price) {
return -1;
} else {
return 1;
}
}
}
3 файл:
import java.util.TreeSet;
public class ComparableTest{
public static void main(String[] args){
TreeSet<Guns> gunsTreeSet = new TreeSet<>();
Guns portalGun = new Guns(4.56f, 243_463_244, "Aperture Science", false);
Guns gravityGun = new Guns(4.95f, 356_568, "East Black Mesa", true);
Guns shotGun = new Guns(3.12f, 12_345, "Alliance", true);
gunsTreeSet.add(portalGun);
gunsTreeSet.add(gravityGun);
gunsTreeSet.add(shotGun);
for(Guns h:gunsTreeSet){
System.out.println(h);
}
}
}