Java 中使用 HashMap 的 ArrayList 实现字符串相等?我正在使用 .equals()
我正在尝试从 HashMap 列表中删除项目,并且在查看控制台输出时,很明显被比较的字符串是相等的,并且我正在使用 .equals(String x) 方法进行比较,但是输出的这个不断显示错误,并且没有任何内容从列表中删除。谁能给我一个提示,告诉我我在这里做错了什么?
public void removeWord(String wd) {
Log.println(Log.INFO, "Initial Size", "Initial size" + String.valueOf(allWords.size()));
for (int x = 0; x < allWords.size(); x++) {
Log.println(Log.INFO, "Current Word", allWords.get(x).get("Long") + " " + wd);
Log.println(Log.INFO, "Equality?", String.valueOf(allWords.get(x).get("Long").toUpperCase().equals(wd)));
if (allWords.get(x).get("Long").toUpperCase().equals(wd)) {
allWords.remove(x);
Log.println(Log.INFO, "Removed something", "Removed Something!!!!");
clearAdapter();
}
}
Log.println(Log.INFO, "Size of list", "Size of list" + String.valueOf(allWords.size()));
}
I'm trying to remove items from a List of HashMaps, and when looking at the console output, it's plainly clear that the strings being compared are equal, and I am using the .equals(String x) method to compare, however the output of this continually shows false, and nothing gets removed from the list. Could anyone give me a hint as to what I'm doing wrong here?
public void removeWord(String wd) {
Log.println(Log.INFO, "Initial Size", "Initial size" + String.valueOf(allWords.size()));
for (int x = 0; x < allWords.size(); x++) {
Log.println(Log.INFO, "Current Word", allWords.get(x).get("Long") + " " + wd);
Log.println(Log.INFO, "Equality?", String.valueOf(allWords.get(x).get("Long").toUpperCase().equals(wd)));
if (allWords.get(x).get("Long").toUpperCase().equals(wd)) {
allWords.remove(x);
Log.println(Log.INFO, "Removed something", "Removed Something!!!!");
clearAdapter();
}
}
Log.println(Log.INFO, "Size of list", "Size of list" + String.valueOf(allWords.size()));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在将映射到
"Long"
的字符串的大写值与wd
的原始值进行比较。除非wd
以大写形式传入,否则您可能会失败。尝试使用 < code>equalsIgnoreCase 并通过调用修剪
< /a>.我希望这有帮助!You are comparing the uppercase value of the String mapped to
"Long"
to the original value ofwd
. Unlesswd
is being passed in as uppercase you could be off. Try usingequalsIgnoreCase
and also make sure that both strings don't have leading or trailing spaces by callingtrim
. I hope that helps!当您解决问题时,这可能是由字符串或值中的无关不可见字符引起的 - 也尝试比较日志中的长度 - 您应该使用迭代器来遍历所有单词和迭代器的删除方法,否则您可能会得到一个迭代不一致。
When you solve the problem, which may be caused by extraneous invisible characters in the string or the values - try comparing lengths in your logs as well - you should use an iterator to go over allwords and the iterator's remove method, or you may get an inconsistent iteration.