java映射大小与实际条目不同
我尝试使用this answer中描述的技术将一些类自动关联到一个映射。以下是代码示例:
// How are the implementation classes stored inside the map described
@Component("mapperOne")
public class DataMapper extends AbstractMapper {
...
}
// The abstract class, implementing the interface
public abstract class AbstractMapper implements Mapper<T> {
...
}
// Where the bug is actually occuring
public class MapperFactory {
@Autowired
private Map<String, Mapper<T>> mapperMap;
public void getMapper(String mapper) {
...
Mapper<T> mapper = mapperMap.get(mapper);
...
}
}
我知道我有6个用@Component
注释引用的映射器,但是在调试模式下显示的数据不准确:
- 地图的
size
是6,modCount
是6李> head
引用列表的第一个映射器李>- 地图的
table
仅显示6个值中的3个值强> - 地图的
tail
甚至不在table
中李> keySet
正确地显示了我的地图的6个条目李>
这个问题带来了一个NullPointerException
,因为我试图访问一个不在映射中的映射器(尽管出现在keySet
)。我注意到Spring使用了一个LinkedHashMap
来自动关联这些字段,我不知道它是否有任何后果
那里发生了什么?我不明白。任何帮助都将不胜感激
多谢各位
编辑
Looks like hash collisions, so nothing going wrong there. If hashcode % table.size lands on the same index for 2 keys, their values will end up in the same bucket. You get a sort of linked list of entries at the same index. Are you sure the key you use is right ?
我运行了以下代码段:
for (Map.Entry<String, Mapper<T>> entry : mapperMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.hashCode() % mapperMap.size());
}
这给了我以下的结果:
firstKey : -1
secondKey : -5
thirdKey : 5
fourthKey : -1
fifthKey : 2
sixthKey : 0
所以我们只有一个索引(first
和fourth
)发生冲突。过了一段时间,我又有了一个不相似之处,所以现在我的地图只包含firstKey
和thirdKey
作为具体的实现
共 (0) 个答案