【发布时间】:2014-04-17 15:16:16
【问题描述】:
package vehicles_order;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class vehicles implements Comparable {
String Vehicle;
String Make;
String Type;
double Cost;
public static void main(String[] args){
ArrayList cars = new ArrayList();
cars.add(new vehicles ("CAR","Peugot","3008",12500.00));
cars.add(new vehicles ("CAR","BMW","316",4995.00));
cars.add(new vehicles ("CAR","Ford","Fiesta",2995.00));
Collections.sort(cars);
Iterator itr = cars.iterator();
while(itr.hasNext()){
Object element = itr.next();
System.out.println(element + "\n");
}
}
public vehicles(String vehicle, String make, String type, double cost){
Vehicle = vehicle;
Make = make;
Type = type;
Cost = cost;
}
public String toString() {
return "Vehicle: " + Vehicle + "\n" + "Make: " + Make + "\n" + "Type: " + Type + "\n" + "Cost: " + Cost;
}
public int compareTo(Object o1) {
if (this.Cost == ((vehicles) o1).Cost)
return 0;
else if ((this.Cost) > ((vehicles) o1).Cost)
return 1;
else
return -1;
}
}
我的比较器在底部,我只是想知道它实际上是如何工作的。我猜它就像一个堆栈,当它返回 1 时,如果它的 -1 向下移动,它就会向上移动堆栈。
另外,谁能告诉我如何通过不同的方法订购汽车。例如,将成本存储在临时最高值中,并检查新值是否高于当前值
【问题讨论】:
-
该类应命名为
Vehicle,并应实现泛型接口Comparable<Vehicle>,字段名称应为驼峰式(即类型、成本等)
标签: java comparison compare