简体   繁体   English

在Java中实例化布尔对象:Boolean.TRUE和Boolean.FALSE与原语

[英]Instantiating Boolean object in Java: Boolean.TRUE and Boolean.FALSE vs primitives

I want to figure out whether 我想弄清楚是否

Boolean var = true;

is any better than 有什么比

Boolean var = Boolean.True;

?

What is an ideological way? 什么是思想方法? Which one is better comparing performance? 比较效果哪个更好?

After all why there're instantiated Boolean objects if we have two primitives to use? 毕竟,如果我们有两个要使用的原语,为什么还要实例化布尔对象?

Your two snippets perform identically, because the Java compiler will autobox primitives to their wrapper types (which means the code is effectively identical). 您的两个代码片段具有相同的性能,因为Java编译器会将原语自动装箱为其包装类型(这意味着代码实际上是相同的)。 The primitive type boolean would typically be expected to have slightly better performance, if you did boolean var = true; 如果您执行了boolean var = true;则通常会期望原始类型boolean具有更好的性能boolean var = true; (but it probably isn't measurable). (但可能无法测量)。

Go for Boolean.TRUE; Boolean.TRUE;

The reason 原因

boolean boolVar = Boolean.TRUE;

works is because of autounboxing, a Java 5 feature that allows a wrapper object to be converted to its primitive equivalent automatically when needed. 之所以起作用,是因为自动拆箱是Java 5的一项功能,该功能允许包装器对象在需要时自动转换为其等效的原始对象。 The opposite, autoboxing, is also possible: 相反,自动装箱也是可能的:

Boolean boolVar = true;

Boolean.TRUE is a reference to an object of the class Boolean, on the other hand, true is value of the primitive boolean type. Boolean.TRUE是对Boolean类的对象的引用,另一方面, true是原始布尔类型的值。 Boolean class is often called "wrapper classes", and are used when you need an object instead of a primitive type. 布尔类通常称为“包装器类”,在需要对象而不是原始类型时使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM