如何在 LinkedHashMap 中保存大量元素?
How to save a large number of elements in a LinkedHashMap?
我有大量元素要保存在 LinkedHashMap
中。问题是我确实有很多元素,即超过 Integer
class 的大小。由于LinkedHashMap
classreturns一个int
的size()
方法,我认为LinkedHashMap
中的元素个数不能超过int
的可能性。那正确吗?如果是,我该怎么办?
我还应该提到,我实际上并不知道我的代码中到底哪里出现了问题。这只是我的猜测,问题出在 LinkedHashMap
的 size()
方法上。我只是得到与 here.
相同的错误
我不认为拥有如此大量值的地图是个好主意,但如果你真的想继续使用它,你可以覆盖 LinkedHashMap
并使用 BigInteger
class 增加尺寸。
public class MyLinkedHashMap<K,V> extends LinkedHashMap<K,V> {
BigInteger mySize;
@Override
public V put(K key, V Value) {
if (super.put(key,value) == null) // this will still eventually throw an exception because of the 'size' variable incrementing internally in the HashMap
mySize.add(BigInteger.ONE);
}
@Override
public V remove(Object key) {
if (super.remove(key) != null)
mySize.subtract(BigInteger.ONE);
}
@Override
public int size() {
throw new UnsupportedOperationException();
}
public BigInteger getSize() {
return mySize;
}
}
请注意,由于您无法更改 size()
方法的 return 类型,因此您必须创建自己的大小方法和变量来检索地图的大小。
此外,您实际上可能需要覆盖 HashMap
本身,因为它的 put()
方法仍会增加现有的 size
变量 int
值并最终导致它超出 Java 整数的范围。
最后,需要明确的是,这 根本不是 一个好主意,因为尝试以这种方式重新利用现有数据结构有很多陷阱(例如忘记覆盖 modify/use size
变量的其他方法,可能损害原始数据结构有效性的程序员错误,或其他实例 variables/side 最初从未打算处理如此大尺寸的效果等.).
我有大量元素要保存在 LinkedHashMap
中。问题是我确实有很多元素,即超过 Integer
class 的大小。由于LinkedHashMap
classreturns一个int
的size()
方法,我认为LinkedHashMap
中的元素个数不能超过int
的可能性。那正确吗?如果是,我该怎么办?
我还应该提到,我实际上并不知道我的代码中到底哪里出现了问题。这只是我的猜测,问题出在 LinkedHashMap
的 size()
方法上。我只是得到与 here.
我不认为拥有如此大量值的地图是个好主意,但如果你真的想继续使用它,你可以覆盖 LinkedHashMap
并使用 BigInteger
class 增加尺寸。
public class MyLinkedHashMap<K,V> extends LinkedHashMap<K,V> {
BigInteger mySize;
@Override
public V put(K key, V Value) {
if (super.put(key,value) == null) // this will still eventually throw an exception because of the 'size' variable incrementing internally in the HashMap
mySize.add(BigInteger.ONE);
}
@Override
public V remove(Object key) {
if (super.remove(key) != null)
mySize.subtract(BigInteger.ONE);
}
@Override
public int size() {
throw new UnsupportedOperationException();
}
public BigInteger getSize() {
return mySize;
}
}
请注意,由于您无法更改 size()
方法的 return 类型,因此您必须创建自己的大小方法和变量来检索地图的大小。
此外,您实际上可能需要覆盖 HashMap
本身,因为它的 put()
方法仍会增加现有的 size
变量 int
值并最终导致它超出 Java 整数的范围。
最后,需要明确的是,这 根本不是 一个好主意,因为尝试以这种方式重新利用现有数据结构有很多陷阱(例如忘记覆盖 modify/use size
变量的其他方法,可能损害原始数据结构有效性的程序员错误,或其他实例 variables/side 最初从未打算处理如此大尺寸的效果等.).