在java中创建Nullables类型 [英] Creating Nullables types in java

查看:121
本文介绍了在java中创建Nullables类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

int? someTestInt;

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

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 ,你可能想要使用 Integer 类:

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 Integer class:

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

每个基元都有相应的类: Character Double 字节等。'标准库'数值类都扩展了 数字 类。

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

请注意Java autoboxes 这些对象,因此您可以像使用原语一样使用并声明它们(不需要例如 new Integer(1))。所以,虽然它们在技术上是对象(因此,扩展 Object 类,原始 int 类型不),你可以用它们做基本的算术。它们在编译时转换为对象操作。

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

这篇关于在java中创建Nullables类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆