我用谷歌搜索了它,并尝试了一些例子,但我总是陷入困境。
这是当我尝试使用 Collections.sort
时出现的错误消息:
The generic method
sort(List<T>)
of typeCollections
is not applicable for the arguments (ArrayList<HashMap<String,String>>
). The inferred typeHashMap<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/