我有一个Java HashMap用于存储一些基本的字符串值:
Map<String, String> map = new HashMap<String, String>();
map.put("Id", task.getStorageId());
map.put("Name", task.getName());
map.put("Description", task.getDescription());
Run Code Online (Sandbox Code Playgroud)
在一种用法下,Id条目会被条目覆盖Description,每次都不会失败.我在调试器中看过它 - Id插入正常,Name插入正常,然后Descroption插入时,它会覆盖Id条目.在应用程序的另一部分使用完全相同的代码和密钥,它没有任何问题.完全糊涂了.这里发生了什么?
编辑
也许我应该提到(尽管它似乎没有相关性),这是在Android上发生的,而不是在JVM中.这可能是问题吗?我也发现很难相信,但代码块就像提供的代码片段一样简单.我将尝试捆绑一个演示它并在某个地方发布的Android应用.
您可能没有看到的条目存在,请查看表的modCount,您应该看到正确的条目数.这意味着发生了哈希冲突.基本上,2个键被散列到表中的同一个桶中.如果您查看具有原始密钥的存储桶,则它具有下一个字段,该字段是指向您认为丢失的其他条目的指针.
没有发生在我身上:
import java.util.Map;
import java.util.HashMap;
public class MapDemo
{
public static void main(String[] args)
{
Map<String, String> map = new HashMap<String, String>();
map.put("Id", "task.getStorageId()");
map.put("Name", "task.getName()");
map.put("Description", "task.getDescription()");
System.out.println("map: " + map);
}
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
com.intellij.rt.execution.application.AppMain MapDemo
map: {Name=task.getName(), Description=task.getDescription(), Id=task.getStorageId()}
Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2652 次 |
| 最近记录: |