前提・実現したいこと
HashTable の #keys(key を全て取り出したい) と #loadFactor(bucket のサイズの平均値を求めたい)を実装したいのですが、どうすればよいのかさっぱり分かりません。アイデアを頂けないでしょうか?
HashTableEntry
Java
1public class HashTableEntry<K, V> { 2 3 private K key; 4 private V value; 5 private int hash; 6 7 public HashTableEntry(K key, V value) { 8 if (key == null) 9 throw new IllegalArgumentException("key cannot be null"); 10 11 this.key = key; 12 this.value = value; 13 this.hash = key.hashCode(); 14 } 15 16 public K getKey() { 17 return this.key; 18 } 19 20 public V getValue() { 21 return this.value; 22 } 23 24 public int getHashCode() { 25 return this.hash; 26 } 27 28 public String toString() { 29 return "{" + key + ": " + value + " (" + hash + ")}"; 30 } 31 32}
HashTable
Java
1import java.util.List; 2import java.util.LinkedList; 3import java.util.Arrays; 4 5 6public class HashTable<K, V> { 7 8 private Object[] entries; 9 10 private List<HashTableEntry<K, V>> bucket(int i) { 11 return (List<HashTableEntry<K, V>>)entries[i]; 12 } 13 14 public HashTable(int numBuckets) { 15 if (numBuckets < 1) 16 throw new IllegalArgumentException("hash table must have at least one bucket"); 17 this.entries = new Object[numBuckets]; 18 for (int i = 0; i < numBuckets; i++) 19 this.entries[i] = new LinkedList<HashTableEntry<K, V>>(); 20 } 21 22 public void put(K key, V value) { 23 HashTableEntry<K, V> e = new HashTableEntry<K, V>(key, value); 24 int h = e.getHashCode(); 25 int b = Math.abs(h % this.entries.length); 26 bucket(b).add(e); 27 } 28 29 public V get(K key) { 30 int h = key.hashCode(); 31 int b = Math.abs(h % this.entries.length); 32 for (HashTableEntry<K, V> e : bucket(b)) 33 if (key.equals(e.getKey())) 34 return e.getValue(); 35 return null; 36 } 37 38 public List<K> keys() { 39 List<K> klist = new LinkedList<K>(); 40 } 41 42 public double loadFactor() { 43 double sum = 0; 44 }
今更思ったが、キー重複の処理は?
キーの重複を解消できてないということでしょうか?確認してみます、、
回答1件
あなたの回答
tips
プレビュー