为什么布尔包装器类实现Serializable接口和Comparable接口?有什么用?

编程入门 行业动态 更新时间:2024-10-19 21:29:09
本文介绍了为什么布尔包装器类实现Serializable接口和Comparable接口?有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么布尔和字符包装类正在实现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接口?有什么用?

本文发布于:2023-06-07 15:19:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568521.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   布尔   什么用   Serializable   Comparable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!