定义真,假,未设定状态的最佳方法 [英] Best way to define true, false, unset state

查看:148
本文介绍了定义真,假,未设定状态的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有,你需要知道在哪里没有设置一个布尔值(例如,如果该取消设置值应该从父继承值)在Java布尔原语(和其它语言的相当值)的情况显然是不足够了。

什么是实现这一目标的最佳做法?定义一个新的简单的类,它能够EX pressing全部三种状态,或者使用Java Boolean类和使用null表示未设定状态?


解决方案

 一个Boolean = TRUE;
布尔B = FALSE;
布尔C = NULL;

我会使用它。这是最直接的。

另一种方法是使用一个枚举。也许这就是更好,更快,因为不需要拳击:

 公共枚举三态{
    真正,
    假,
    TRALSE
};

有是第一的优势,你的类的用户并不需要关心你的三态布尔值。他们还可以通过真正。如果你不喜欢,因为它告诉,而一些关于它的意义在这里,你仍然可以做一个公共静态最终布尔tralse = NULL ; 在你的类

If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.

What's the best practice to achieve this? Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?

解决方案

Boolean a = true;
Boolean b = false;
Boolean c = null;

I would use that. It's the most straight-forward.

Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required:

public enum ThreeState {
    TRUE,
    FALSE,
    TRALSE
};

There is the advantage of the first that users of your class doesn't need to care about your three-state boolean. They can still pass true and false. If you don't like the null, since it's telling rather little about its meaning here, you can still make a public static final Boolean tralse = null; in your class.

这篇关于定义真,假,未设定状态的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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