英文:
Map with long as key in Java
问题
我的性能分析器显示,我在很大一部分时间里将 long
包装成 Long
,而我想避免这样做。我目前这样做是因为我使用了 Map<Long, V>
。是否有一种常见的方法可以创建一个键为 long
的 Map 呢?
我知道它不会是 Map<long, V>
,因为类型系统不允许这样做,但这并不意味着不能存在从 long
到 V
的映射。实际上,这很容易实现,因为我只需要复制 HashMap<K,V>
的代码,将 K
替换为 long
,并进行类型系统所需的所有更改(例如,键的迭代不再是 Iterator<K>
)。
我的问题是是否已经存在这样的库,或者我应该自己动手实现?
背景是我的性能分析器显示,在进行批处理时,三分之一的时间用于将 long
转换为 Long
,而没有任何理由为了类型系统而支付这个代价。
英文:
My profiler state I spend an important part of the time wrapping long
into Long
which I want to avoid. I currently do it because I use Map<Long, V>
. Is there an usual way to create a Map whose keys are long
?
I know it won't be a Map<long, V>
because the type system does not allow it, but that does not mean that a map from long
to V
can't exists. Actually, it would be quite easy to do, since I would just need to copy the code of HashMap<K,V>
, replace K
by long
, and do all changes required by the type system (E.g. iteration over key would not be an Iterator<K>
anymore)
My question is does such a library already exists, or should I do it myself ?
The context is that my profiler state that, when doing batch processing, a third of the time is spent transforming long
into Long
, and there is really no reason to accept to pay this price for the type system
答案1
得分: 1
http://fastutil.di.unimi.it/ 是一个完全符合我之前提问的库的类。
英文:
http://fastutil.di.unimi.it/ is a class of library doing exactly what I was asking for here
答案2
得分: 0
这是不受支持的,因为泛型不支持原始类型。你也不能创建一个包含原始类型的类(比如 HashMap<int,V>
)。
也许JEP 218 - 原始类型上的泛型将在未来尝试解决这个问题。
建议:
- 你能否将代码的其余部分直接使用
Long
类型来代替? - Long 类在范围 -127 到 128 内缓存数值(代码)。探索是否能够为更大范围的值实现类似的内部缓存。
英文:
This is not supported as generics does not support primitive types. You cannot create a class with primitive types as well (like HashMap<int,V>
).
Maybe the JEP 218 - Generics over Primitive Types will look to solve this in the future.
Suggestions:
- Can you change the rest of the code to use a
Long
in the first place? - The Long class caches values from -127 to 128 (code). Explore if you could have a similar internal cache for a bigger range.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论