英文:
HashMap<String, Boolean> getValue returns Boolean but java tries to cast to String
问题
ArrayList<HashMap<String, Boolean>> list = new ArrayList<>();
for (Sound s: drumThumper.soundsToe) {
HashMap<String, Boolean> l = new HashMap<>();
l.put("name", s.getSound().replace(".wav", ""));
l.put("checkbox", s==drumThumper.selectedSoundToe);
list.add(l);
}
SimpleAdapter simpleAdapter = new SimpleAdapter(activity.getApplicationContext(), list, R.layout.checkbox_list, new String[]{"name", "checkbox"}, new int[]{R.id.name, R.id.checkbox});
listPopupWindow.setAdapter(simpleAdapter);
listPopupWindow.setOnItemClickListener((parent, view1, position, id) -> {
HashMap<String, Boolean> item = list.get(position);
Map.Entry<String, Boolean> entry = item.entrySet().iterator().next();
Boolean oldValue = entry.getValue();
entry.setValue(!oldValue);
});
英文:
ArrayList<HashMap<String, Boolean>> list = new ArrayList<>();
for (Sound s: drumThumper.soundsToe) {
HashMap l = new HashMap<String, Boolean>();
l.put("name", s.getSound().replace(".wav", ""));
l.put("checkbox", s==drumThumper.selectedSoundToe);
list.add(l);
}
SimpleAdapter simpleAdapter = new SimpleAdapter(activity.getApplicationContext(), list, R.layout.checkbox_list, new String[]{"name", "checkbox"}, new int[]{R.id.name, R.id.checkbox});
listPopupWindow.setAdapter(simpleAdapter);
listPopupWindow.setOnItemClickListener((parent, view1, position, id) -> {
HashMap<String, Boolean> item = list.get(position);
Map.Entry<String,Boolean> entry = item.entrySet().iterator().next();
Boolean oldValue = entry.getValue();
entry.setValue(!oldValue);
});
but I'm getting java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
on
at lambda$onToeLongClick$1(Dialogues.java:165)
Boolean oldValue = entry.getValue();
How can that be possible? The HashMap is obviously from String
to Boolean
. And I'm calling .getValue
which even the intellisense says returns a Boolean
答案1
得分: 2
你在使用HashMap
时收到了关于使用原始类型的警告,而警告正是因为这个原因存在。当你写下:
l.put("name", s.getSound().replace(".wav", ""));
你正在将一个String
值放入映射中,尽管你之前承诺只放入Boolean
值。
我无法详细建议如何重新修改这段代码,因为你的意图并不完全清楚,但我会指出,通常使用Set<K>
比使用Map<K, Boolean>
更容易。
英文:
You're getting a warning about using a raw type where you have HashMap
listed, and the warning is there for exactly this reason. When you say
l.put("name", s.getSound().replace(".wav", ""));
you are putting a String
value into the map even though you promised only to put Boolean
s in it.
I can't advise on how exactly to best rework this code, since it's not entirely clear what your intention is, but I will note that it's usually easier to use a Set<K>
instead of a Map<K, Boolean>
.
答案2
得分: 2
你的问题在这里:
l.put("name", s.getSound().replace(".wav", ""));
你在HashMap中放入了两个字符串。当你尝试获取布尔值时,它找到了一个字符串。
英文:
your problem is here:
l.put("name", s.getSound().replace(".wav", ""));
you put inside HashMap 2 strings. And when you try to get boolean value, he find a string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论