为什么布尔包装器类实现Serializable接口和Comparable接口?有什么用? [英] Why Boolean wrapper class implements Serializable interface and Comparable interface ? What is the use of it?

查看:62
本文介绍了为什么布尔包装器类实现Serializable接口和Comparable接口?有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么布尔和字符包装类正在实现Serializable接口和Comparable接口?它有什么用?

Why Boolean and Character wrapper classes are implementing Serializable interface and Comparable interface ? What is the use of it?

推荐答案

Java 5 ,以解决错误 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 中,

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接口?有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆