Java 21中的两个值得关注的Bug修复
source link: https://www.didispace.com/java-features/java21/java-21-2-bugfix.html#identityhashmap%E7%9A%84remove-key-value-%E5%92%8Creplace-key-value-newvalue-%E7%9A%84%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在Java 21中,除了推出很多新特性之外,一些Bug修复,也需要注意一下。因为这些改变可能在升级的时候,造成影响。
# Double.toString()
和Float.toString()
的精度问题修复
比如:对于Double.String(1e23)
:
- 在Java 19后,输出内容为:
1.0E23
- 在Java 18中,输出内容为:
9.999999999999999E22
# IdentityHashMap
的remove(key, value)
和replace(key, value, newValue)
的错误处理
IdentityHashMap
是Java中自带的一个集合,是一个比较特殊的Map实现。它使用的是恒等比较(而不是equals方法)来判断两个键是否相等。
这意味着,对于同一个对象的不同引用,IdentityHashMap
会将它们视为不同的键,而其他Map
实现类则会将它们视为相同的键。
在Java 20之前(不含Java 20)IdentityHashMap
中的remove(key, value)
和replace(key, value, newValue)
方法,错误地将值参数与映射中的值进行了equals比较,这使得remove(key, value)
和replace(key, value, newValue)
方法执行结果不如预期。
如下例子所示,Java 20之前是不对的,但Java 20之后可以正确实现了。
var users = new IdentityHashMap<String, User>();
String key = "abc";
users.put(key, new User("Jane Doe"));
var removed = users.remove(key, new User("Jane Doe"));
assert !removed;
如果您学习过程中如遇困难?可以加入我们超高质量的技术交流群open in new window,参与交流与讨论,更好的学习与进步!另外,不要走开,关注我!持续更新Java新特性专栏open in new window!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK