Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 数组排序问题:2个不同的排序结果_Java_Sorting_Comparable - Fatal编程技术网

Java 数组排序问题:2个不同的排序结果

Java 数组排序问题:2个不同的排序结果,java,sorting,comparable,Java,Sorting,Comparable,我需要根据三个参数对列表进行排序。我就是这样做的 SortedVehicles = new ArrayList<MyVehicle>(vehicles); Collections.sort(SortedVehicles,Collections.reverseOrder()); @Override public int compareTo(ITSVehicle v) { if (this.getCapacity(0) < v.getCapacity(0))

我需要根据三个参数对列表进行排序。我就是这样做的

SortedVehicles = new ArrayList<MyVehicle>(vehicles);
        Collections.sort(SortedVehicles,Collections.reverseOrder());
@Override
public int compareTo(ITSVehicle v) {
    if (this.getCapacity(0) < v.getCapacity(0)) return 1;
    if (this.getCapacity(0) > v.getCapacity(0)) return -1;
    if (this.getCapacity(0) == v.getCapacity(0))
    {
        if (this.getCapacity(1) < v.getCapacity(1)) return 1;
        if (this.getCapacity(1) > v.getCapacity(1)) return -1;
    }
    if (this.getCapacity(1) == v.getCapacity(1))
    {
        if (this.getCapacity(2) < v.getCapacity(2)) return 1;
        if (this.getCapacity(2) > v.getCapacity(2)) return -1;
    }
    return 0;
}

您的方法的问题很可能是您正在将
Double
s与
=
进行比较。 在大多数情况下,
newdouble(x)==newdouble(x)
是错误的,因为
=
测试对象的均衡性。您必须在此处使用
equals()
(或自己取消装箱)

只是一个小提示:您可能希望使用原始包装器的
compareTo
方法,例如:

public int compareTo(ITSVehicle v) {
  result = this.getCapacity(0).compareTo(v.getCapacity(0));
  if( result == 0 ) {
    result = this.getCapacity(1).compareTo(v.getCapacity(1));
  }
  if( result == 0 ) {
    result = this.getCapacity(2).compareTo(v.getCapacity(2));
  }

  return result;
}
请注意,如果任何容量为空,这将中断,但您的方法也是如此(由于自动(un)装箱将抛出NPE,因此很难跟踪异常)


如果它们不能为空,则可能需要考虑使用图元来代替。您的数据已经表明容量具有不同的含义,因此从设计角度来看,最好不要将其存储在列表等中(我假设您会这样做,因此需要您使用

Double
,而不是
Double
)。

我假设您使用的是原语,是吗?@Thomas:你是什么意思?返回的数据类型是什么?@Thomas:v.getCapacity()返回双精度(不是双精度)这是问题所在,我会补充一个答案。你建议使用双精度而不是双精度吗Double@KlausosKlausos见我最后的补充。
public int compareTo(ITSVehicle v) {
  result = this.getCapacity(0).compareTo(v.getCapacity(0));
  if( result == 0 ) {
    result = this.getCapacity(1).compareTo(v.getCapacity(1));
  }
  if( result == 0 ) {
    result = this.getCapacity(2).compareTo(v.getCapacity(2));
  }

  return result;
}