我想在我的查詢結果中得到min distance, min speed and max speed
的記錄。目前我正在獲得最短距離,但我面臨的問題是獲得最小和最大速度,我在問自己是否可以在BehaviourItem
課程中添加另一個public int compareTo(BehaviourItem otherItem)
方法來達到該目的,但我得到的錯誤爲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);
}
}
,你可以創建自定義'Comparator's並傳遞給'Collection.sort'方法 – user902383