早上好/晚上好,我是爪哇的初学者。我正在为一个程序制作一个类,在这个类中,人们可以使用各种变量(州、国家、纬度等)来设置位置,作为练习为一个项目使用多个类的一种方式。在这个类(称为Location)中,我被迫以一种以前从未使用过的方式使用compareTo(),因为我正在实现Comparable类。我知道compareTo()是用来比较字符串的,看它们是相同还是不同,但这一次我是在一个方法中比较两个对象。我如何对方法中的这些对象进行排序,同时仍然返回一个int?
目前,这是我的Location类。我只会发布当前的方法,但根据论坛中的其他帖子,展示类的一大部分是很好的。
public class Location implements Comparable<Location> {
//Done for now
private String state;
private String county;
private double latitude;
private double longitude;
private int elevation;
public Location(String state, String county) throws IllegalArgumentException {
this.state = state;
this.county = county;
}
//...
//various getters and setters for mentioned variables...
//...
public int compareTo(Location a){ //must compare objs and return an int
int result = this.compareTo(a);
if (result == 0){
// the equal
return result;
} else if (result < 0){
//not equal, one would be higher than the other
return result;
} else{
//Same as comment above
return result;
}
}我一直在论坛和一些专注于java的网站上寻找帮助,但他们只是以我习惯使用该方法的方式来展示它(想想s1.comparesTo(s2))。我还没有偶然发现任何涉及实现Comparable的帖子。
发布于 2021-10-12 05:34:53
为什么不欺骗并使用Comparator构建器呢?
public class Location implements Comparable<Location> {
private static final Comparator<Location> comparator = Comparator.comparing((Location l) -> l.state)
.thenComparing(l -> l.county)
.thenComparingDouble(l -> l.latitude)
...;
public int compareTo(Location a) {
return comparator.compare(this, a);
}
}另一种方法是手动比较字段,如果不为零则返回结果,否则转到下一个字段并重复。
发布于 2021-10-12 05:41:12
我也是java的初学者,如果我的解释有问题,请原谅。接口Comparable是用来排序的,所以首先你必须告诉我们你想要排序的依据。例如,您可以按以下方式按高程对位置进行排序:
public int compareTo(Location a){ //must compare objs and return an int
if(elevation < a.getElevation()){
return -1;
}
else if(elevation == a.getElevation()){
return 0;
}
else
return 1;
}希望我的回答对你有帮助,并祝你成功。
https://stackoverflow.com/questions/69535471
复制相似问题