Why Boolean and Character wrapper classes are implementing Serializable interface and Comparable interface ? What is the use of it?
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
.
Initially, there was pushback from no less than 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.
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.
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.
It implements Serializable so that an object containing it can be serialized. Not making it Serializable would be a serious limitation.
The Comparable isn't so useful as there is only two possible values, so it is likely to be for consistency with other wrappers.
Note: Void
is not serializable or comparable, but it can only be null
which is serializable.
To use any primitive in most of the Collection classes, they have to implement Comparable. Without the wrapper, you couldn't use a primitive in any ordered Collection classes. Also, as a pure primitive, it doesn't have an equals method, so any key based Collection class wouldn't work.
Here's one. Try instantiating ArrayList<T>
with a boolean
...
© 2022 - 2024 — McMap. All rights reserved.
what is the use of it
? – Cavafy