前提・実現したいこと
HashTable の #includesKey
//key が含まれているなら true、ないなら false
を実装したいのですが、以下のコードであっているでしょうか?自信がありません。
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 boolean includesKey(K key) { 39 for (HashTableEntry<K, V> e : bucket(this.entries.length)) 40 if (key.equals(e.getKey())) 41 return true; 42 return false; 43 } 44 45}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/08/05 02:08 編集
2018/08/05 02:33
退会済みユーザー
2018/08/05 04:01
2018/08/05 04:20
退会済みユーザー
2018/08/05 06:09