在 Java 中创建 Nullables 类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1123544/
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-10-29 15:15:04  来源:igfitidea点击:

Creating Nullables types in java

javanullable

提问by RC1140

I am trying to create a nullalble object in Java but no idea how to do this , in C# this would be done like this

我试图在 Java 中创建一个 nullalble 对象,但不知道如何做到这一点,在 C# 中这将是这样完成的

int? someTestInt;

This allows me to check for for null , while in certain cases i can use a 0 value ,this isnt always possible since certain execution paths allow 0 values

这允许我检查 null ,而在某些情况下我可以使用 0 值,这并不总是可能的,因为某些执行路径允许 0 值

回答by Henrik Paul

I'm not entirely sure what you want, but if you want to have an integer value that also can be declared null, you probably want to use the Integerclass:

我不完全确定你想要什么,但如果你想要一个也可以声明的整数值null,你可能想要使用这个Integer类:

Integer nullableInteger = 1;
nullableInteger = null;
System.out.println(nullableInteger); // "null"

There are corresponding classes for each primitive: Character, Long, Double, Byte, etc. The 'standard library' numeric classes all extend the Numberclass.

每个基元都有相应的类:CharacterLongDoubleByte等。“标准库”数字类都扩展了Number该类。

Note that Java autoboxesthese objects automatically since JDK 1.5, so you can use and declarethem just like the primitives (no need for e.g. "new Integer(1)"). So, although they are technically objects (and, therefore, extend the Objectclass, which the primitive inttype does not), you can do basic arithmetics with them. They are converted to object operations at compile time.

请注意,自 JDK 1.5 起,Java自动这些对象进行自动装箱,因此您可以像使用原语一样使用和声明它们(不需要例如“ new Integer(1)”)。因此,尽管它们在技术上是对象(因此扩展Object了原始int类型所没有的类),但您可以使用它们进行基本的算术运算。它们在编译时转换为对象操作。

回答by Peter Recore

Java does not support nullable primitives. You can use the Integer type if you want the ability to store nulls.

Java 不支持可为空的原语。如果您希望能够存储空值,则可以使用 Integer 类型。

(This is a duplicate of this post: How to present the nullable primitive type int in Java?)

(这是这篇文章的副本: 如何在 Java 中呈现可为空的原始类型 int?

回答by mkmurray

Perhaps try the Integer type in Java.

也许试试 Java 中的 Integer 类型。