How to instantiate the Java Boolean wrapper class?

In Java, I can write code like this

Boolean b = true ;

It will work. I now have an object with a value of "true"

How does this work? Why can't I pass values through constructors? like this:

Boolean b = new Boolean( true ) ;

In addition, can I implement custom classes in a similar way? What if so?

So I can do something like this:

Foobar foobar = "Test" ;

So I have my own packaging class

thank you

Solution

No, you can't do the latter

The former is called autoboxing and is implemented in Java v1 Automatic packaging is introduced in 5, which is the primitive in the packaging object

When using generics and / or collections, you can clearly see the benefits of automatic boxing:

From article: J2SE 5.0 in a nutshell

In“ Auto@R_196_2419 @ing and Auto- Un@R_196_2419 @In the "ing of primitive types" sample, we have:

Before (auto boxing added)

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0,new Integer(42)); 
int total = (list.get(0)).intValue();

after

ArrayList<Integer> list = new ArrayList<Integer>();
 list.add(0,42);
 int total = list.get(0);

As you can see, the code is clearer

Remember the last note on the document:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>