Java 中的布尔值与布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3728616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:00:04  来源:igfitidea点击:

Boolean vs boolean in Java

javaboolean

提问by Neel

There are discussions around Integervs intin Java. The default value of the former is nullwhile in the latter it's 0. How about Booleanvs boolean?

在 Java 中有关于Integervs 的讨论int。前者的默认值是,null而后者是0. BooleanVSboolean怎么样?

A variable in my application can have 0/1values. I would like to use boolean/Booleanand prefer not to use int. Can I use Boolean/booleaninstead?

我的应用程序中的变量可以有0/1值。我想使用boolean/Boolean而不想使用int. 我可以用Boolean/boolean代替吗?

采纳答案by Jigar Joshi

Yesyou can use Boolean/booleaninstead.

是的,您可以使用Boolean/boolean代替。

First one is Object and second one is primitive type.

第一个是对象,第二个是原始类型。

  • On first one, you will get more methods which will be useful.

  • Second one is cheap considering memory expenseThe second will save you a lot more memory, so go for it

  • 第一个,您将获得更多有用的方法。

  • 考虑到内存费用,第二个很便宜第二个会为您节省更多内存,所以去吧

Now choose your way.

现在选择你的方式。

回答by CoolBeans

You can use the Boolean constants- Boolean.TRUEand Boolean.FALSEinstead of 0and 1. You can create your variable as of type booleanif primitive is what you are after. This way you won't have to create new Booleanobjects.

您可以使用布尔常量- Boolean.TRUEandBoolean.FALSE代替0and 1boolean如果原始类型是您所追求的,您可以将变量创建为类型。这样您就不必创建新Boolean对象。

回答by Buhake Sindi

Booleanwrapsthe boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this

Boolean包装布尔原始类型。在 JDK 5 及更高版本中,Oracle(或 Oracle 购买之前的 Sun)引入了autoboxing/unboxing,这基本上允许您执行此操作

boolean result = Boolean.TRUE;

or

或者

Boolean result = true; 

Which essentially the compiler does,

基本上是编译器所做的,

Boolean result = Boolean.valueOf(true);

So, for your answer, it's YES.

所以,对于你的回答,是的。

回答by Yauhen Yakimovich

I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):

我有点扩展提供的答案(因为到目前为止他们专注于他们的“自己的”/人工术语,专注于对特定语言进行编程,而不是在创建编程语言的场景背后照顾更大的图景,一般来说,即当事情发生时就像类型安全与内存考虑因素有所不同):

int is not boolean

int 不是布尔值

Consider

考虑

    boolean bar = true;      
    System.out.printf("Bar is %b\n", bar);
    System.out.printf("Bar is %d\n", (bar)?1:0);
    int baz = 1;       
    System.out.printf("Baz is %d\n", baz);
    System.out.printf("Baz is %b\n", baz);

with output

带输出

    Bar is true
    Bar is 1
    Baz is 1
    Baz is true

Java code on 3rd line (bar)?1:0illustrates that bar(boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of

第 3 行的 Java 代码(bar)?1:0说明bar( boolean) 不能隐式转换(强制转换)为int。我提出这一点并不是为了说明 JVM 背后的实现细节,而是要指出,就低级考虑(如内存大小)而言,人们确实必须更喜欢值而不是类型安全。特别是如果该类型安全没有像布尔类型那样真正/完全使用,其中检查以

if value \in {0,1} then cast to boolean type, otherwise throw an exception.

如果值 \in {0,1} 然后转换为布尔类型,否则抛出异常。

All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).

只是为了说明 {0,1} < {-2^31, .. , 2^31 -1}。好像有点矫枉过正吧?类型安全在用户定义的类型中确实很重要,而不是在原始类型的隐式转换中(尽管最后一个包含在第一个中)。

Bytes are not types or bits

字节不是类型或位

Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).

请注意,在内存中,{0,1} 范围内的变量仍将至少占用一个字节或一个字(xbits 取决于寄存器的大小),除非特别注意(例如在内存中很好地打包 - 8 "boolean"位转换为 1 个字节 - 来回)。

By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).

通过更喜欢类型安全(例如将值放入/包装到特定类型的盒子中)而不是额外的值打包(例如使用位移或算术),人们确实有效地选择了编写更少的代码而不是获得更多的内存。(另一方面,人们总是可以定义一个自定义用户类型,这将促进所有不值布尔值的转换)。

keyword vs. type

关键字与类型

Finally, your question is about comparing keywordvs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class) or in other words

最后,您的问题是关于比较keywordtype。我认为通过使用/首选关键字(“标记”为原语)而不是类型(使用另一个关键字class 的普通复合用户可定义类)或换句话说,解释为什么或如何准确地获得性能很重要

boolean foo = true;

vs.

对比

Boolean foo = true;

The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitiveand wrappingclasses can be simply translated into inlinevalue (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).

第一个“事物”(类型)不能被扩展(子类化)并且不是没有原因的。有效地,原始类和 包装类的Java 术语可以简单地转换为内联值(一个 LITERAL 或一个常量,只要可以推断替换,编译器就会直接替换它,或者如果不是 - 仍然回退到包装值)。

Optimization is achieved due to trivial:

优化是由于微不足道的:

"Less runtime casting operations => more speed."

“更少的运行时转换操作 => 更高的速度。”

That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).

这就是为什么当实际的类型推断完成时,它可能(仍然)在必要时(或转换/转换成这样)用所有类型信息实例化包装类。

So, the difference between booleanand Booleanis exactly in Compilationand Runtime(a bit far going but almost as instanceofvs. getClass()).

因此,booleanBoolean之间的区别正是在编译运行时(有点远,但几乎就像instanceofgetClass())。

Finally, autoboxing is slower than primitives

最后,自动装箱比基元慢

Note the fact that Java can do autoboxingis just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safetyis the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicitcode) would be critical e.g. for if-then-else flow controls.

请注意,Java 可以进行自动装箱这一事实只是一种“语法糖”。它不会加速任何事情,只是让您编写更少的代码。就是这样。仍然执行类型信息容器的转换和包装。出于性能原因,选择算法将始终跳过创建具有类型信息的类实例以实现类型安全的额外内务处理。缺乏类型安全是您为获得性能而付出的代价。对于具有布尔值表达式的代码,类型安全(当您编写较少的隐式代码时)将是至关重要的,例如对于 if-then-else 流控制。

回答by Sachin Jadhav

Basically boolean represent a primitive data type where Boolean represent a reference data type. this story is started when Java want to become purely object oriented it's provided wrapper class concept to over come to use of primitive data type.

基本上 boolean 表示原始数据类型,其中 Boolean 表示参考数据类型。这个故事开始于 Java 想要成为纯面向对象的时候,它提供了包装类概念来取代原始数据类型的使用。

boolean b1;
Boolean b2;

b1and b2are not same.

b1并且b2不一样。

回答by Sudip Bhandari

One observation: (though this can be thought of side effect)

一个观察:(虽然这可以被认为是副作用)

booleanbeing a primitive can either say yes or no.

boolean是一个原始类型,可以说是或否。

Booleanis an object (it can refer to either yes or no or 'don't know' i.e. null)

Boolean是一个对象(它可以指是或否或“不知道”即空)

回答by Witold Kaczurba

You can use Boolean / boolean. Simplicity is the way to go. If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).

您可以使用布尔值/布尔值。简单是要走的路。如果您不需要特定的 api(集合、流等)并且您没有预见到您会需要它们 - 使用它的原始版本(布尔值)。

  1. 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; }

  2. Use Boolean when you need an object, eg:

    • Stream of Booleans,
    • Optional
    • Collections of Booleans
  1. 使用原语,您可以保证不会传递空值。
    你不会落入这样的陷阱。下面的代码抛出 NullPointerException(来自:Booleans、conditional operators 和 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; }

  2. 当您需要一个对象时使用布尔值,例如:

    • 布尔值流,
    • 可选的
    • 布尔值的集合