为什么布尔和字符包装类正在实现Serializable接口和Comparable接口?它有什么用?
Why Boolean and Character wrapper classes are implementing Serializable interface and Comparable interface ? What is the use of it?
推荐答案可比较 接口已添加到 Boolean 中的类 Java 5 ,以解决错误 JDK-4329937 ,以及至少一个.引用的问题之一是在 JTable .
The Comparable interface was added to the Boolean class in Java 5, to address bug JDK-4329937, and at least one other. One of the issues cited was sorting boolean columns in a JTable.
最初,不少于 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. ...
我们愿意牺牲这种设计纯度".在实用主义的祭坛上,但我不相信确实需要比较布尔值.要对布尔值列表进行排序非常罕见.更常见的是要基于此字段对包含布尔字段的对象列表进行排序,但是这样做需要使用Comparator.无论如何,如果您正在编写比较器,即使布尔本身不实现Comparable,也可以基于Boolean字段进行排序很简单.
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.
但是几年后,该实用程序得到了认可:
But several years later, the utility was acknowledged:
多年来,很明显,如果我们提供此功能,它将使人们的生活更加轻松.
Over the years it has become apparent that it would make life easier for people if we provided this functionality.
自从实施了此增强功能以来,它就变得更加有用.例如,在 Java 8 中, 比较器 类新方法 comparing()和 thenComparing ,它们可以基于字段构建比较器.并且,将布尔字段作为排序条件的一部分可能是合理且有用的.
Since this enhancement was implemented, it's become even more useful. For example, in Java 8, the Comparator class introduced new methods comparing() and thenComparing, that can build a comparator based on fields. And it can be reasonable and useful to include a boolean field as part of sort criteria.
更多推荐
为什么布尔包装器类实现Serializable接口和Comparable接口?有什么用?
发布评论