【发布时间】:2019-01-27 01:36:57
【问题描述】:
我正在尝试对传递的 ArrayLists HashMap 进行选择排序,但我有点卡住了。我不确定如何使它成为适用于整数、双精度和字符串的通用方法。我看过与此类似的过去问题,但我仍然不明白。感谢任何帮助或指导。
public static HashMap sort_list(HashMap lists) {
HashMap sorted_lists = new HashMap();
ArrayList<Integer> sorted_ints = new ArrayList<>();
ArrayList<Double> sorted_doubles = new ArrayList<>();
ArrayList<String> sorted_strings = new ArrayList<>();
ArrayList list_of_ints = (ArrayList) lists.get("ints");
ArrayList list_of_doubles = (ArrayList) lists.get("doubles");
ArrayList list_of_strings = (ArrayList) lists.get("strings");
//My sort code below (which doesn't work with this implementation)
int min;
for(int i = 0; i < arr.size() - 1; i++) {
min = i;
for(int j = i + 1; j < arr.size(); j++) {
if(arr.get(j) < arr.get(min)) {
min = j;
}
}
int temp = arr.get(min);
arr.set(min, arr.get(i));
arr.set(i, temp);
}
// return hashmap
return sorted_lists;
}
【问题讨论】:
-
不要使用 raw 泛型类型。始终在
HashMap和ArrayList之后添加<...>。 -
目前还不清楚您要排序的是什么。
arr是什么? --- 此外,您不能有List的int值,因为原始类型不能与泛型一起使用。你的意思是list_of_ints可能是ArrayList<Integer>吗? --- 为什么不直接调用sort()方法? -
@Andreas:是的,但是如果有一个明智的
<..., ValueType>,那么这个问题几乎已经可以回答了。关键是:使用像这样的异构列表类型闻起来像是设计错误。 真的很难证明这种代码的合理性。
标签: java sorting arraylist hashmap