我正在尝试在查询结果中获取min distance, min speed and max speed的记录。目前,我正在获得最短的距离,但是我面临着获取最小和最大速度的问题,我在问自己是否可以在public int compareTo(BehaviourItem otherItem)类中添加另一个BehaviourItem方法来达到这一目标,但是我遇到了错误Duplicate method compareTo(BehaviourItem) in type BehaviourItem

如何从BehaviourItem类获得最小和最大速度?

代码:

         PreparedStatement prepared = con
                 .prepareStatement("SELECT speed, stop_distance from behaviour where mac = ? and stop_name = ?");
                 prepared.setString(1, macD);
                 prepared.setString(1, sto_nam);
                 ResultSet rsBehav = prepared.executeQuery();
                 List<BehaviourItem> behavList = new ArrayList<BehaviourItem>();
                 while (rsBehav.next()) {
                     int distance = rsBehav.getInt("stop_distance");
                     int speed = rsBehav.getInt("speed");
                     BehaviourItem behItem = new BehaviourItem(distance, speed);
                     behavList.add(behItem);

                 }
                 Collections.sort(behavList);
                 int minDistance =  behavList.get(0).getDistance();

BehaviourItem类:
public class BehaviourItem implements Comparable<BehaviourItem>{
    int speed;
    int distance;

    public BehaviourItem(int speed, int distance) {
        super();
        this.speed = speed;
        this.distance = distance;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public int getDistance() {
        return distance;
    }

    public void setDistance(int distance) {
        this.distance = distance;
    }

    @Override
    public int compareTo(BehaviourItem otherItem) {
        // TODO Auto-generated method stub
        return Integer.compare(this.distance, otherItem.distance);
    }

}

最佳答案

您不应该让BehaviourItem实现Comparable,因为它没有自然顺序。相反,为不同的属性实现不同的 Comparator s

请注意,在Java 8中,您可以像这样简单地实现Comparator

Comparator<BehaviourItem> orderBySpeed=Comparator.comparingInt(BehaviourItem::getSpeed);

相当于
Comparator<BehaviourItem> orderBySpeed=new Comparator<BehaviourItem>() {
    public int compare(BehaviourItem a, BehaviourItem b) {
        return Integer.compare(a.getSpeed(), b.getSpeed());
    }
};

要么
Comparator<BehaviourItem> orderByDistance
                         =Comparator.comparingInt(BehaviourItem::getDistance);

对于其他财产。

几乎所有使用订单的收集方法都有一个重载,它支持传递Comparator来定义订单,而不是使用自然订单:
Collections.sort(behavList, orderBySpeed);

分别
Collections.sort(behavList, orderByDistance);

您甚至可以临时创建比较器:
Collections.sort(behavList, Comparator.comparingInt(BehaviourItem::getDistance));


Collections.sort(behavList, Comparator.comparingInt(BehaviourItem::getSpeed));

但是即使没有排序,流API仍允许您查找最小值或最大值:
Optional<BehaviourItem> minBySpeed=behavList.stream()
                       .max(Comparator.comparingInt(BehaviourItem::getSpeed));

09-30 10:00