【发布时间】:2016-03-18 01:03:06
【问题描述】:
我有一个哈希图,它包含键 - 字符串类型 - 奶酪对象数组:
public void testing(){
HashMap<String, ArrayList<cheese>> one = new HashMap<>();
ArrayList<cheese> two = new ArrayList<>();
cheese seven = new cheese("59");
cheese eight = new cheese("60");
cheese nine = new cheese("12");
cheese ten = new cheese("15");
two.add(seven);
two.add(eight);
two.add(nine);
two.add(ten);
one.put("hello", two);
}
这是我的奶酪课:
public class cheese {
String num;
public cheese(String num){
this.num = num;
}
public String getString(){
return num;
}
}
我想获取 ArrayList 并对 ArrayList 中的每个元素进行排序,然后将对象放回哈希映射中。
这是 java。我知道这听起来很疯狂但也很有趣!
我考虑过使用比较器和 TreeMaps,但它们似乎不适合这个问题。 任何指针都会有所帮助。
【问题讨论】:
-
可以的,列表在地图中的时候可以直接排序;你可以做
Collections.sort(one.get("hello"))。 -
试过了,它不起作用,因为数组中的东西是奶酪对象T_T,如果它们是整数或字符串值,那么它工作正常:) 感谢您的回复
-
然后致电
Collections.sort(one.get("hello"), thisCheeseComparatorIJustWrote)。 -
我在这个解决方案中看到一个问题,它使用字符串作为数字。无论如何,您都需要将其转换为数字类型,因为字符串使用字典排序。不确定你是否需要它。
-
@GDT 请不要忘记查看答案并选择其中一个有助于解决您的问题。干杯!
标签: java arrays sorting hashmap