在Java中有关于Integer和int的讨论。前者的默认值为null,而后者的默认值为0。布尔和布尔呢?

我的应用程序中的变量可以有0/1的值。我想使用布尔/布尔,而不喜欢使用int。我可以用布尔/布尔代替吗?


当前回答

布尔值是线程安全的,所以您可以考虑这个因素以及答案中列出的所有其他因素

其他回答

是的,你可以用布尔/布尔来代替。

第一个是对象,第二个是基本类型。

第一个,你会得到更多有用的方法。 考虑到内存消耗,第二种方法很便宜。第二种方法会节省你更多的内存,所以试试吧

现在选择你的道路。

你可以使用Boolean / Boolean。简单才是正确之道。 如果你不需要特定的api(集合,流等),并且你没有预见到你会需要它们-使用它的原始版本(布尔)。

With primitives you guarantee that you will not pass null values. You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing): public static void main(String[] args) throws Exception { Boolean b = true ? returnsNull() : false; // NPE on this line. System.out.println(b); } public static Boolean returnsNull() { return null; } Use Boolean when you need an object, eg: Stream of Booleans, Optional Collections of Booleans

布尔值是线程安全的,所以您可以考虑这个因素以及答案中列出的所有其他因素

你可以使用布尔常数-布尔。TRUE和布尔值。FALSE而不是0和1。你可以创建你的变量类型布尔,如果原始是什么,你是之后。这样你就不必创建新的布尔对象了。

Boolean包装布尔原语类型。在JDK 5及以上版本中,Oracle(或Oracle收购之前的Sun)引入了自动装箱/解装箱,这基本上允许您这样做

boolean result = Boolean.TRUE;

or

Boolean result = true; 

这基本上是编译器做的,

Boolean result = Boolean.valueOf(true);

所以,你的答案是肯定的。