如何在Java中呈现可为空的原始类型int? [英] How to present the nullable primitive type int in Java?

查看:372
本文介绍了如何在Java中呈现可为空的原始类型int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个实体类,它有一个名为documentYear的字段,可能有无符号整数值,如1999,2006等。同时,这个字段也可能是未知,也就是说,不知道哪一年文档已创建。

I am designing an entity class which has a field named "documentYear", which might have unsigned integer values such as 1999, 2006, etc. Meanwhile, this field might also be "unknown", that is, not sure which year the document is created.

因此,C#中可以为空的 int 类型将非常适合。但是,Java没有像C#那样可以为空的特性。

Therefore, a nullable int type as in C# will be well suited. However, Java does not have a nullable feature as C# has.

我有两个选择,但我不喜欢它们:

I have two options but I don't like them both:


  1. 使用 java.lang.Integer 而不是基本类型 int ;

  2. 使用-1表示未知值

  1. Use java.lang.Integer instead of the primitive type int;
  2. Use -1 to present the "unknown" value

有没有人有更好的选择或想法?

Does anyone have better options or ideas?

更新:我的实体类将拥有数万个实例;因此,java.lang.Integer的开销可能对系统的整体性能来说太重了。

Update: My entity class will have tens of thousands of instances; therefore the overhead of java.lang.Integer might be too heavy for overall performance of the system.

推荐答案

你要去必须抛弃原始类型或使用一些任意的int值作为无效年份。

You're going to have to either ditch the primitive type or use some arbitrary int value as your "invalid year".

负值实际上是一个不错的选择,因为几乎没有机会一个有效的年份会导致整数溢出并且没有有效的负年份。

A negative value is actually a good choice since there is little chance of having a valid year that would cause an integer overflow and there is no valid negative year.

这篇关于如何在Java中呈现可为空的原始类型int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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