基于Type </type>的一个字段对List <type>进行排序

时间:2015-01-11 06:16:28

标签: java sorting

我有一个班级:

private class Venue
{
    private int venueID;
    private String venueName;
    private String venueLocation;
    private String startDate;
    private int startHour;
    private String startHourType;
    private int startMinute;
    private String endDate;
    private int endHour;
    private String endHourType;
    private int endMinute;
    private String runningTime;
    private double distance;
}

我有一个该类的列表对象:

private List<Venue> venueList;

我使用Web服务调用的结果填充venueList,例如

Venue newVenue = new Venue();
newVenue.venueName = "value";
newVenue.distance = 1518.23
//snip
venueList.add(newVenue);

现在我想根据.distance字段对objectplaceList进行排序,所以我有这个:

Collections.sort(venueList, new Comparator<Venue>() {
    public int compare(Venue one, Venue other) {
        return Double.compare(one.distance, other.distance);
    }
});

然而,这并没有按预期排序,例如List可能看起来像:

Distance:
1512.9027099609375
702.6363525390625
814.787353515625
605.23388671875

排序列表的顺序是相同的。我错过了什么?

编辑:结果应该是最低的(605.233)到最高(1512.902)

编辑:我的自定义排序类:

public class LocationComparator implements Comparator<Venue> {
    @Override
    public int compare(Venue one, Venue other) {
        return Double.compare(other.distance, one.distance);
    }

}

我称之为:

Collections.sort(venueList, new LocationComparator());

哪个是对的,对吧?

3 个答案:

答案 0 :(得分:2)

更改以下声明

return Double.compare(one.distance, other.distance);

以下,

return Double.compare(other.distance, one.distance);

答案 1 :(得分:1)

这很奇怪。这是一个简单的测试:

public class Test {

    public static void main(String[] args) {
        List<Item> itemsToSort = new LinkedList<Item>();
        for (double d = 100; d > 0; d -= 15) {
            Item item = new Item();
            item.doubleValue = d;
            itemsToSort.add(item);
        }

        System.out.println("Before Sort:");
        System.out.println(itemsToSort);

        Collections.sort(itemsToSort, new Comparator<Item>() {

            @Override
            public int compare(Item i1, Item i2) {
                return Double.compare(i1.doubleValue, i2.doubleValue);
            }

        });
        System.out.println("Sorted:");
        System.out.println(itemsToSort);
    }

    private static class Item {
        private double doubleValue;

        @Override
        public String toString() {
            return "Item: " + doubleValue;
        }
    }
}

,输出为:

Before Sort:

[Item: 100.0, Item: 85.0, Item: 70.0, Item: 55.0, Item: 40.0, Item: 25.0, Item: 10.0]

Sorted:

[Item: 10.0, Item: 25.0, Item: 40.0, Item: 55.0, Item: 70.0, Item: 85.0, Item: 100.0]

所以它似乎按照记录的方式工作。

答案 2 :(得分:0)

您是否尝试过Venueimplements Comparable<Venue>?您必须覆盖compareTo()方法:

public int compareTo (Venue other) {
   return Double.compare(this.distance, other.distance);
}

然后,当您需要对Collection进行排序时,您只需要致电:

Collections.sort(venueList);