Java原语封装选择的方式;避免“魔法”原语
我正在编写一个程序,它创建大量大型数组来存储数据。所有这些数据都必须保存在 RAM 中,因此我避免使用对象,并且当前使用 Shorts 来节省空间。这些 Shorts 作为 ID 号,可以放入查找类中以按需获取相应的对象。我最近质疑我是否需要整个 2 个字节的 Short,所以我现在想知道是否有办法定义存储在代码中一个位置的数据类型,以便我可以轻松更改它,而无需寻找当前设置为短的每个演员、返回类型等。
如果我愿意使用对象,我可以轻松地
class MySmallNumber extends Short{}
在必要时更改父类。
如果这是 C/C++,我可以使用它
#define small short
来实现我正在寻找的效果。
我正在寻找一种在 java 中执行类似操作的方法,不需要在数组中存储 64 位对象引用。非常感谢任何帮助。现在我正在寻找一个非常混乱的 IDE 来替换所有内容来做到这一点。
I'm writing a program which creates a large number of large arrays to store data. All of this data has to held in RAM, so I'm avoiding objects and currently using shorts to save space. These shorts serve as ID numbers which can be put into a lookup class to get the corresponding object on demand. I have recently questioned whether I'll need the whole 2 bytes of a short, and so I'm now wondering if there's anyway to define the data type being stored in one place in my code so that I can change it easily without having to hunt down every cast, return type, etc. that is currently set to short.
If I were willing to use objects I could easily just do
class MySmallNumber extends Short{}
and change the parent class if necessary.
If this were C/C++, i could use
#define small short
for the effect I'm looking for.
I'm searching for a way to do something like this in java that won't require storing 64-bit object references in my arrays. Any help is greatly appreciated. Right now I'm looking at a really messy IDE replace all in order to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将数组封装在一些自定义类中。它不应该增加大量的空间开销,因为您使用大型数组。
在代码中的所有其他地方,您都可以使用 long。当您将这些长整型传递给数组自定义类时,您可以将其转换为您在其中使用的长整型。
最后,您只需在这一类中进行更改。
You can incapsulate you array in some custom class. It shouldn't add considerable space overhead because you work with large arrays.
In all other places in your code you can use long. When you pass these longs to you array custom class you can convert it to the one you use inside it.
Finally you have to make changes in this one class only.
我建议将所有依赖于 ID 值类型的代码分解到一个单独的类中。让该类处理所有依赖于 ID 值是短、字节还是其他值的操作(包括查找)。您可以将单个值作为
short
甚至int
值传入和传出,即使它们在内部转换为byte
也是如此。 (例如,java.io.DataOutputStream.writeByte(int)
的编写方式是这样的——它接受int
参数并将其视为byte< /代码> 值。)
I would suggest factoring out all code that depends on the type of your ID values into a separate class. Let that class handle all the operations (including lookup) that depend on whether the ID values are
short
,byte
, or something else. You can pass individual values in and out asshort
or evenint
values, even if internally they are converted tobyte
. (This is, for instance, howjava.io.DataOutputStream.writeByte(int)
was written—it takes anint
argument and treats it as abyte
value.)不太确定你在这里追求什么,但这可能很有趣:
not quite sure what you are after here, but this may be of interest: