android - 对 HashMap 列表进行排序

标签 android listview sorting hashmap

我用谷歌搜索了它,并尝试了一些例子,但我总是陷入困境。

这是当我尝试使用 Collections.sort 时出现的错误消息:

The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<HashMap<String,String>>). The inferred type HashMap<String,String> is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>.

我的代码与此类似。

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

//Get the data (see above)
JSONObject json = JSONfunctions.getJSONfromURL("http://xxxxxxxxxxxxxxxxxxxxxx");

try {
    //Get the element that holds the earthquakes ( JSONArray )
    JSONArray earthquakes = json.getJSONArray("earthquakes");

    //Loop the Array
    for (int i = 0; i < earthquakes.length(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject e = earthquakes.getJSONObject(i);

        map.put("id", String.valueOf(i));
        map.put("name", "Earthquake name:" + e.getString("eqid"));
        map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
        mylist.add(map);
    }
} catch (JSONException e) {
    Log.e("log_tag", "Error parsing data " + e.toString());
}

ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.main,
        new String[]{"name", "magnitude"},
        new int[]{R.id.item_title, R.id.item_subtitle});

setListAdapter(adapter);

最佳答案

发生此错误的原因是您无法简单地比较 HashMap 的两个实例。

当您在列表上调用 sort 方法时,Java 将尝试相互比较每个元素并对集合进行排序。如果元素无法比较(没有明显的方法来比较两个 HashMap,标准是什么?),就会发生错误。

您真的需要对该列表进行排序吗?如果是的话,按照什么标准?

实现这一目标的唯一方法是您创建自己的 Comparator并使用它来比较 HashMap 的实例,同时考虑您的特定条件。

关于android - 对 HashMap 列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11295215/

相关文章:

javascript - ExtJS 数据存储不排序

ios - 用于在 Objective-C 中对二维数组进行排序的优于 O(n^2) 的算法

java - 如何使用另一个线程从方法中获取结果

java - Android ListView 只显示最新的项目

android - 如何在android Tab 中使用ListView?

android - 列出在线声音的最佳策略是什么?

python - 使用特定键的顺序对字典列表进行排序

android - 如何随机启动Android Activity?

android - flurry 记录 session 但不记录事件(android)

java - Android:Outputstream.write - 问题