【问题标题】:How can I make a generic sort method to sort a HashMap of ArrayLists of multiple types?如何制作通用排序方法来对多种类型的 ArrayLists 的 HashMap 进行排序?
【发布时间】: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 泛型类型。始终在HashMapArrayList 之后添加&lt;...&gt;
  • 目前还不清楚您要排序的是什么。 arr 是什么? --- 此外,您不能有 Listint 值,因为原始类型不能与泛型一起使用。你的意思是list_of_ints 可能是ArrayList&lt;Integer&gt; 吗? --- 为什么不直接调用sort() 方法?
  • @Andreas:是的,但是如果有一个明智的&lt;..., ValueType&gt;,那么这个问题几乎已经可以回答了。关键是:使用像这样的异构列表类型闻起来像是设计错误。 真的很难证明这种代码的合理性。

标签: java sorting arraylist hashmap


【解决方案1】:

Java 已经提供了对Lists 进行排序的工具,前提是List 中的元素实现了Comparable 接口。它被称为Collections.sortcheck it out。这是进行“通用排序”的正确方法:完全按照Collections.sort 的要求实现适当的接口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多