如何创建整数和字符串对的列表(或其他类型的容器),允许两个对中的重复项并且可以按整数值排序?
我需要用名称(字符串)和评分(整数)对填充容器,容器必须允许名称和评分中的重复值,我需要按评分值对此列表进行排序.
我尝试使用SortedMap但不允许重复值:
SortedMap<Integer,String> sm=new TreeMap<Integer, String>();
sm.put(23, "Peter");
sm.put(11, "Tony");
sm.put(110, "Claire");
sm.put(13, "ferca");
sm.put(55, "Julian");
sm.put(13, "Pedro");
Run Code Online (Sandbox Code Playgroud)
在这个例子中,ferca和Pedro具有相同的得分值,这是我需要允许的,但是SortedMap用"Pedro"覆盖"ferca".
这样做的最佳容器类型是什么?
aio*_*obe 11
由于您希望订购您的收藏品,我建议您使用List和Collections.sort.如果您决定采用这种方法,您仍有两种选择:
Comparator可以作为参数传递给的自定义sort,或Score类实现Comparable<Score>以下是后一种方法的示例和ideone演示:
import java.util.*;
class Score implements Comparable<Score> {
int score;
String name;
public Score(int score, String name) {
this.score = score;
this.name = name;
}
@Override
public int compareTo(Score o) {
return score < o.score ? -1 : score > o.score ? 1 : 0;
}
}
public class Test {
public static void main(String[] args){
List<Score> scores = new ArrayList<Score>();
scores.add(new Score(23, "Peter"));
scores.add(new Score(11, "Tony"));
scores.add(new Score(110, "Claire"));
scores.add(new Score(13, "ferca"));
scores.add(new Score(55, "Julian"));
scores.add(new Score(13, "Pedro"));
Collections.sort(scores);
}
}
Run Code Online (Sandbox Code Playgroud)
class包含这两个字段的内容Comparator基于int值比较两个对象的自定义.list对象Collection.sort(); 通过comparator这里的obj
class MyEntity{
int val;
String name;
}
List<MyEntity> list = new ArrayList<MyEntity>();
list.add(new MyEntity(1,"a"));
list.add(new MyEntity(4,"z"));
list.add(new MyEntity(2,"x"));
Collections.sort(list,new MyComparator());
class MyComparator implements Comparator<MyEntity>{
public int compare(MyEntity ob1, MyEntity ob2){
return ob1.getVal() - ob2.getVal() ;
}
}
Run Code Online (Sandbox Code Playgroud)注意:这只是展示基本概念的模型
| 归档时间: |
|
| 查看次数: |
29099 次 |
| 最近记录: |