- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
public static void main(String args[]) throws Exception {
ConcurrentHashMap<byte[], Integer> dps =
new ConcurrentHashMap<byte[], Integer>();
System.out.println(dps.putIfAbsent("hi".getBytes(), 1));
System.out.println(dps.putIfAbsent("hi".getBytes(), 1));
}
打印
null
null
为什么它不在第二行打印 1
?我已经阅读了 putIfAbsent 的语义,并且应该保证它可以工作。 (注意:这是从大型并发程序中提炼出来的......如您所见,它现在是单线程的。)
最佳答案
putIfAbsent() not working with ConcurrentHashMap
"hi".getBytes()
不是常量数组,因此您将在那里生成两个不同的对象。如果您执行了类似以下操作,您将看到您的 1
。
byte[] bytes = "hi".getBytes();
System.out.println(dps.putIfAbsent(bytes, 1));
System.out.println(dps.putIfAbsent(bytes, 1));
byte[]
数组上的 hashCode()
和 equals(...)
方法来自 Object
它只查看对象的引用,而不是其内容。
每当您在Map
中存储某些内容时,您都需要确保它覆盖hashCode()
和equals(...)
方法,除非您只想比较引用文献。这是 Java 常见问题解答。请参阅这些文档:Java theory and practice: Hashing it out .
正如 @Mauren 在评论中提到的,要使用 byte[]
的内容,您必须编写一个包装 byte 的小类[]
并提供适当的 hashCode()
和 equals(...)
方法。或者正如 @CostiCiudatu 提到的,您可以使用 SortedMap
并使用 Comparator
for byte[]
来查看数组的内容。
顺便说一句,如果String.getBytes()
返回一个new byte[]
,根据您的StringCoding.StringEncoder
类进行编码字符集等.
关于java - putIfAbsent() 不适用于 ConcurrentHashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19124737/
我是一名优秀的程序员,十分优秀!