0

所以我似乎遇到了一个小问题。我试图用一个字符串存储一些双打(就像它们的名字一样),然后能够按降序对它们进行排序。

我还想以某种方式存储它们,例如 hashmap、arraylist、list 等……我不确定哪个是最好的。

有点像让我们假设这些以某种方式存储,如哈希图、列表等......

Bob: 6.0
Mary: 5.4
Bill: 6.3
Ann: 5.0
Jim: 6.0

然后将它们输出到类似的东西:

Bill: 6.3
Bob: 6.0 //Notice, it must be able to support duplicates. 
Jim: 6.0
Mary: 5.4
Ann: 5.0

我希望这对其他人有意义,如果不让我知道,我可以尝试清除它。

PS 我寻找其他类似的线程,但找不到适合我需要的线程。

编辑:我似乎找到了一种可行的方法......如果你有兴趣看到,我在这里有一个 pastebin 链接:http: //pastebin.com/qWJbD5MZ

现在,代码是基于 Bukkit API 构建的,所以它可能对其他人没有多大用处。

4

3 回答 3

9

最简单的方法是创建一个包装类:

class Person {
    String name;
    double score;
    //constructor, getters etc.
}

然后把这些人放在一个列表中:

List<Person> list = Arrays.asList(new Person("Bob", 6),
                                  new Person("Mary", 5.4),
                                  new Person("Bill", 6.3),
                                  new Person("Ann", 5.0),
                                  new Person("Jim", 6.0));

最后使用自定义比较器对它们进行排序,比较分数:

Collections.sort(list, comparator);

比较器可能如下所示:

Collections.sort(list, new Comparator<Person>() {

    @Override
    public int compare(Person o1, Person o2) {
        //sort by score
        if (o1.score != o2.score)
            return Double.compare(o1.score, o2.score);
        //if same score, sort by name
        return o1.name.compareTo(o2.name);
    }
});
于 2013-08-08T06:21:42.267 回答
2

如果您不需要能够通过键查找值,最简单的方法是定义一个具有名称和整数属性的类型,然后java.lang.Comparable通过比较整数值让它实现接口,并且将数据存储在 TreeSet 中以获取排序集合。

如果您想让这些值能够通过字符串值查找并按整数排序,您可能必须组合两个数据结构。您可以通过将数据存储在 HashMap 中同时拥有一个排序集合来做到这一点,尽管您必须做一些工作来保持两个结构之间的数据同步。

于 2013-08-08T06:24:08.840 回答
0

您可以使用Arrays.sort方法

public class Test {
  public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
     Person[] personArray = {new Person("Bob", 6), new Person("Mary", 5.4), new Person("Bill", 6.3),new Person("Ann", 5.0),new Person("Jim", 6.0)};

    Arrays.sort(personArray,new MyComparator());
    for(Person person:personArray){
        System.out.println(person.getName()+"  : "+person.getScore());
    }

}

}
class Person {
 String name;
 double score;

Person(String name, double score) {
    this.name=name;
    this.score = score;

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public double getScore() {
    return score;
}

public void setScore(double score) {
    this.score = score;
}

}
class MyComparator implements Comparator<Person> {

@Override
public int compare(Person o1, Person o2) {
    return o1.name.compareTo(o2.name);
}

}
于 2013-08-08T06:37:40.780 回答