作者:loushuyu60 | 来源:互联网 | 2023-06-07 15:41
IwanttolimitthemaximumsizeofaHashMaptotakemetricsonavarietyofhashingalgorithmstha
I want to limit the maximum size of a HashMap
to take metrics on a variety of hashing algorithms that I'm implementing. I looked at the loadfactor in one of HashMap
's overloaded constructors.
我想限制HashMap的最大大小,以对我正在实现的各种散列算法进行度量。我在HashMap的重载构造函数中查看了loadfactor。
HashMap(int initialCapacity, float loadFactor)
I tried setting the loadFactor to 0.0f in the constructor (meaning that I don't want the HashMap to grow in size EVER) but javac
calls this invalid:
我在构造函数中尝试将loadFactor设置为0.0f(这意味着我不希望HashMap的大小永远增长),但javac将其称为无效:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal load factor: 0.0
at java.util.HashMap.(HashMap.java:177)
at hashtables.CustomHash.(Main.java:20)
at hashtables.Main.main(Main.java:70) Java Result: 1
Is there another way to limit the size of HashMap
so it doesn't grow ever?
有没有另一种方法来限制HashMap的大小,这样它就不会永远增长?
5 个解决方案
1
The method put
in the HashMap class is the one in charge of adding the elements into the HashMap and it does it by calling a method named addEntry which code is as follows:
HashMap类中的方法是负责将元素添加到HashMap中的方法,它通过调用一个名为addEntry的方法来实现它,该方法代码如下:
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry e = table[bucketIndex];
table[bucketIndex] = new Entry(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
As you can see in this method is where the HashMap is resized if the threshold has been exceeded, so I would try extending the class HashMap and writing my own methods for put
and addEntry
in order to remove the resizing. Something like:
正如您在这个方法中看到的,如果阈值已经超过了,HashMap将被调整大小,所以我将尝试扩展类HashMap并编写自己的put和addEntry方法,以删除调整大小。喜欢的东西:
package java.util;
public class MyHashMap extends HashMap {
private V myPutForNullKey(V value) {
for (Entry e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
myAddEntry(0, null, value, 0);
return null;
}
public V myPut(K key, V value) {
if (key == null)
return myPutForNullKey(value);
if (size e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
myAddEntry(hash, key, value, i);
}
return null;
}
void myAddEntry(int hash, K key, V value, int bucketIndex) {
Entry e = table[bucketIndex];
table[bucketIndex] = new Entry(hash, key, value, e);
size++;
}
}
You would need to write your own methods since put
and addEntry
cannot be overriding and you would also need to do the same for putForNullKey
since it is called inside put
. A validation in put
is required to verify that we are not trying to put an object if the table is full.
您需要编写自己的方法,因为put和addEntry不能重写,而且您还需要对putForNullKey执行相同的操作,因为它被称为inside put。put的验证需要验证,如果表已经满了,我们不会尝试放入一个对象。