排序HashMap列表

时间:2012-07-02 13:59:26

标签: android listview sorting hashmap

我已经谷歌了,并尝试了一些例子,但我总是陷入困境。

当我尝试使用Collections.sort

时,这是错误消息
  

类型sort(List<T>)的通用方法Collections不适用于参数(ArrayList<HashMap<String,String>>)。推断类型HashMap<String,String>不是有界参数<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);

2 个答案:

答案 0 :(得分:3)

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

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

你真的需要对该列表进行排序吗?如果是这样,按哪个标准?

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

答案 1 :(得分:1)

正如@pcalcao已经解释的那样,您需要决定如何对地图进行排序(基于什么标准),然后在自定义比较器中实现该排序顺序,并使用该比较器调用Collections.sort。

例如,假设您想按名称的字母顺序排序,您可以编写如下内容:

Collections.sort(mylist, new Comparator<Map<String, String>>() {

    @Override
    public int compare(Map<String, String> o1, Map<String, String> o2) {
        String name1 = o1.get("name");
        String name2 = o2.get("name");
        if (name1 == null) return -1;
        return name1.compareTo(name2);
    }
});
相关问题