gpt4 book ai didi

java - 为什么 Boolean 包装类实现 Serialized 接口(interface)和 Comparable 接口(interface)?它有什么用呢?

转载 作者:行者123 更新时间:2023-12-01 08:15:16 24 4
gpt4 key购买 nike

为什么 boolean 和字符包装类要实现 Serialized 接口(interface)和 Comparable 接口(interface)?它有什么用?

最佳答案

Comparable接口(interface)已添加到 Boolean类(class) Java 5 ,解决错误 JDK-4329937 ,以及至少另外一个。引用的问题之一是对 JTable 中的 boolean 列进行排序.

最初,来自不少于 Joshua Bloch 的抵制:

The current design is consistent with the language itself: it is a compile-time error to attempt to compare two booleans for order:

if (true < false)  // ERROR: WON'T COMPILE
foo();

The wrapper class (Boolean) merely mirrors the behavior of the wrapped primitive. ...

We would be willing to sacrifice this "design purity" on the altar of pragmatism, but I'm not convinced that there is a real need for comparing Booleans. It is extraordinarily rare to want to sort a list of Booleans. More common is to want to sort a list of objects containing a Boolean field based on this field, but doing this requires the use of a Comparator. If you're writing a Comparator anyway, it's straightforward to sort based on the Boolean field even though Boolean does not, itself, implement Comparable.

但几年后,这种实用性得到了认可:

Over the years it has become apparent that it would make life easier for people if we provided this functionality.

自从实现此增强功能以​​来,它变得更加有用。例如,在Java 8中,Comparator类引入了新方法 comparing()thenComparing,可以基于字段构建比较器。将 boolean 字段作为排序标准的一部分包含在内是合理且有用的。

关于java - 为什么 Boolean 包装类实现 Serialized 接口(interface)和 Comparable 接口(interface)?它有什么用呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13892403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com