简体   繁体   中英

Does Java allow nullable types?

In C# I can a variable to allow nulls with the question mark. I want to have a true/false/null result. I want to have it set to null by default. The boolean will be set to true/false by a test result, but sometimes the test is not run and a boolean is default to false in java, so 3rd option to test against would be nice.

c# example:

bool? bPassed = null;

Does java have anything similar to this?

No.

Instead, you can use the boxed Boolean class (which is an ordinary class rather a primitive type), or a three-valued enum .

you can use :

Boolean b = null;

that is, the java.lang.Boolean object in Java.

And then also set true or false by a simple assignment:

Boolean b = true; or Boolean b = false;

不,在java 原语中不能有空值,如果你想要这个功能,你可能想要使用布尔代替。

Yes you can.

To do this sort of thing, java has a wrapper class for every primitive type. If you make your variable an instance of the wrapper class, it can be assigned null just like any normal variable.

Instead of:

boolean myval;

... you can use:

Boolean myval = null;

You can assign it like this:

myval = new Boolean(true);

... And get its primitive value out like this:

if (myval.booleanValue() == false) {
  // ...
}

Every primitive type ( int , boolean , float , ...) has a corresponding wrapper type ( Integer , Boolean , Float , ...).

Java's autoboxing feature allows the compiler to sometimes automatically coerce the wrapper type into its primitive value and vice versa. But, you can always do it manually if the compiler can't figure it out.

Sure you can go with Boolean, but to make it more obvious that your type can have "value" or "no value", it's very easy to make a wrapper class that does more or less what ? types do in C#:

public class Nullable<T> {
    private T value;
    public Nullable() { value = null; }
    public Nullable(T init) { value = init; }
    public void set(T v) { value = v; }
    public boolean hasValue() { return value != null; }
    public T value() { return value; }
    public T valueOrDefault(T defaultValue) { return value == null ? defaultValue : value; }
}

Then you can use it like this:

private Nullable<Integer> myInt = new Nullable<>();
...
myInt.set(5);
...
if (myInt.hasValue()) 
   ....
int foo = myInt.valueOrDefault(10);

Note that something like this is standard since Java8: the Optional class. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

In Java, primitive types can't be null. However, you could use Boolean and friends.

不,但您可以使用Boolean类而不是原始boolean类型来放置null

If you are using object, it allows null

If you are using Primitive Data Types, it does not allow null

That the reason Java has Wrapper Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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