2

我正在尝试Vector使用 Java Collections 框架对列表进行排序。

这是我的代码...

public class RiverList {

    public static void main(String[] args) {
        Vector<River> rivers = new Vector<River>();
        //name length and discharge

        River river3 = new River("Nil", 6852, 2660);
        River river5 = new River("Amazonas", 6448, 209000);
        River river1 = new River("Rhein", 1233, 2330);
        River river4 = new River("Donau", 2857, 6700);
        River river2 = new River("Oker", 128, 12);

        rivers.add(river1);
        rivers.add(river2);
        rivers.add(river3);
        rivers.add(river4);
        rivers.add(river5);

        System.out.println(rivers);

        // sort the river after length with help class collection

        System.out.println(rivers);

        // sort the river after discharge with help class collection

        System.out.println(rivers);
    }
}

public class River {
    private int length;
    private int discharge;
    private String name; 

    public River(String name, int length, int discharge) {
        this.name = name;
        this.length = length;
        this.discharge = discharge;
    }

    // getters and setters
    ...

    public String toString() {
        return name + ", Length = " + length + ", discharge = " + discharge + "\n";
    }
}

这是我所做的,但我被困在如何进一步进行......

public class RiverLengthComparator implements Comparator {
    public int compare(Object arg0, Object arg1) {
        return 0;
    }
}

public class RiverDischargeComparator implements Comparator {
    public int compare(Object o1, Object o2) {
        return 0;
    }
}

输出应该是这样的(河流长度)......

("Nil", 6852, 2660);
("Amazonas", 6448, 209000);
("Donau", 2857, 6700);
("Rhein", 1233, 2330);
("Oker", 128, 12);

而对于河流排放...

("Amazonas", 6448, 209000);
("Donau", 2857, 6700);
("Nil", 6852, 2660);
("Rhein", 1233, 2330);
("Oker", 128, 12);

有人可以帮我解决这个问题。

4

2 回答 2

5

也许您的compare方法应该返回的不是0;) 考虑您想要实现的目标并阅读Comparator接口文档。

也许使用Comparator<River>而不是只是Comparator第一步。

最后,您可能希望与要使用Collections.sort(rivers, new RiverLengthComparator());的比较器一起使用。

于 2012-06-28T11:06:53.120 回答
2
Collections.sort(vector);

顺便说一句,您从这些打印语句中得到什么?

System.out.println(rivers);

//sort the river after length with help class colection

System.out.println(rivers);

//sort the river after discharge with help class colection


System.out.println(rivers);
于 2012-06-28T11:10:40.720 回答