だから私はハッシュマップクラスを持っていて、それはうまく動作しますが、次のように内容を出力したいです:
1 -> 101 -> 201 (this is a bucket for handling collision) 2
3 - > 103 - > 203
4
5
言い換えれば、プログラムにハッシュテーブルの内容を出力して、そのように見せる方法を知りたいだけです。アドバイスや提案をいただければ幸いです。私はハッシュマップが初めてなので、これは非常に混乱しています。
そして、私はそれを行う方法がわかりません。
これが役立つ場合、これは私のハッシュマップクラスです:
public class HashMap<K, V> {
private int DEFAULT_CAPACITY = 10;
private MapEntry<K, V>[] Hash;
private int size;
public HashMap() {
Hash = new MapEntry[DEFAULT_CAPACITY];
}
public int getHashCode(K key) {
int bucketIndex = key.hashCode() % Hash.length;
return bucketIndex;
}
public V get(K key) {
if (key == null) {
throw new IllegalArgumentException("Null Key!");
}
MapEntry<K, V> entry = Hash[getHashCode(key)];
while (entry != null && !key.equals(entry.getKey()))
entry = entry.getNext();
if (entry != null)
return entry.getValue();
else
return null;
}
/**
*
* @param key
* @param value
* The put method works by associating the specified value with
* the given key in the map.
* If the key is already in the map,
* the old value is replaced with the new one.
*/
public void put(K key, V value) {
int keyBucket = hash(key);
MapEntry<K, V> temp = Hash[keyBucket];
while (temp != null) {
if ((temp.key == null && key == null)
|| (temp.key != null && temp.key.equals(key))) {
temp.value = value;
return;
}
temp = temp.next;
}
Hash[keyBucket] = new MapEntry<K, V>(key, value);
size++;
}
/**
*
* @param key
* @param value
* The delete method works similarly to the put method.
* It locates the desired value in the hash, e,
* and then it removes e from the bucket, like removing a node
* from a linked list.
* Then it sets the value of e to its next node.
* And then it decreases the size of the map.
*/
public void delete(K key, V value) {
if (key == null) {
throw new IllegalArgumentException("Null Key!");
}
int keyBucket = hash(key);
MapEntry<K, V> e = Hash[keyBucket];
while (e != null) {
if ((e.key == null && key == null)
|| (e.key != null && e.key.equals(key))) {
e.value = value;
return;
}
e = e.next;
}
Hash[keyBucket] = new MapEntry<K, V>(key, value);
size--;
}
public void print(){
//THIS IS WHERE I NEED HELP
}
private int hash(K key) {
if (key == null) {
return 0;
} else {
return Math.abs(key.hashCode() % this.Hash.length);
}
} }