How to present the nullable primitive type int in Java?

后端 未结 13 965
灰色年华
灰色年华 2020-12-03 13:29

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 b

相关标签:
13条回答
  • 2020-12-03 13:55

    If you're going to save memory, I would suggest packing several years in a single int. Thus 0 is nil. Then you can make assumptions in order to optimize. If you are working only with the current dates, like years 1970—2014, you can subtract 1969 from all of them and get into 1—55 range. Such values can be coded with only 6 bits. So you can divide your int which is always 32 bit, into 4 zones, with a year in there. This way you can pack 4 years in the range 1970—2226 into a single int. The more narrow your range is, like only 2000—2014 (4 bits), the more years you can pack in a single int.

    0 讨论(0)
  • 2020-12-03 13:57

    Another option is to have an associated boolean flag that indicates whether or not your year value is valid. This flag being false would mean the year is "unknown." This means you have to check one primitive (boolean) to know if you have a value, and if you do, check another primitive (integer).

    Sentinel values often result in fragile code, so it's worth making the effort to avoid the sentinel value unless you are very sure that it will never be a use case.

    0 讨论(0)
  • 2020-12-03 14:01

    Using the Integer class here is probably what you want to do. The overhead associated with the object is most likely (though not necessarily) trivial to your applications overall responsiveness and performance.

    0 讨论(0)
  • 2020-12-03 14:01

    Using the int primitive vs the Integer type is a perfect example of premature optimization.

    If you do the math:

    • int = N(4)
    • Integer = N(16)

    So for 10,000 ints it'll cost 40,000 bytes or 40k. For 10,000 ints it'll cost 160,000 bytes or 160K. If you consider the amount of memory required to process images/photos/video data that's practically negligible.

    My suggestion is, quit wasting time prematurely optimizing based on variable types and look for a good data structure that'll make it easy to process all that data. Regardless of that you do, unless you define 10K primitive variables individually, it's going to end up on the heap anyway.

    0 讨论(0)
  • 2020-12-03 14:06

    You can use a regular int, but use a value such as Integer.MAX_VALUE or Integer.MIN_VALUE which are defined constants as your invalid date. It is also more obvious that -1 or a low negative value that it is invalid, it will certainly not look like a 4 digit date that we are used to seeing.

    0 讨论(0)
  • 2020-12-03 14:06

    java.lang.Integer is reasonable for this case. And it already implemented Serializable, so you can save just only the year field down to the HDD and load it back.

    0 讨论(0)
提交回复
热议问题