看板 java 關於我們 聯絡資訊
這個作業我們要自己實作只能存正整數 integer 的一個 chained hash table, 然後寫四個 Method 分別是 insert, delete, lookup 跟 print.. 我的問題在 print 這個部份。 資料結構我選擇用 Hashmap, 用 Hash function 算出來的雜湊數存成 Key, Value 則用 LinkedList.. 測試的時候 insert 跟 lookup 都沒問題, 但我要把他 print 出來的時候 卻說所有 Hashmap 的 value (= LinkedList) 是 null.. 我想了很久找不出盲點在哪裡,可不可以請厲害的眾板友指點我一下? 先謝過了! (以下程式碼我就略過 main Method..) public class HashTable { private int a, n, m; private Map<Long, LinkedList<Integer>> ht = new HashMap<Long, LinkedList<Integer>>(); /** * Constructor * @param a, n, m: the parameters for hash function: * h(x) = (a*x mod n) mod m. * and the hashtable should have size of m */ public HashTable(int a, int n, int m){ this.a = a; this.n = n; this.m = m; for(long i = 0; i < m; i++){ ht.put(i, new LinkedList<Integer>()); } } /** * @return ture if x positiv, otherwise false. */ public boolean positiv(int x){ return (x >= 0); } /** * @param value: the object to be inserted in the hashtable * insert the number in the hash table, * index calculate through the hash function given. */ public void insert(int value){ if(positiv(value)){ long key = (a * value % n) % m; ht.get(key).add(value); } } /** * @param value: the object to be found * @return true if the value in the hashtable */ public boolean lookup(int value){ if(!positiv(value)){ return false; } long key = ((a * value) % n) % m; return ht.get(key).contains(value); } /** * @param value: the object to be deleted * Removes the (first) occurrence of the specified element * from this hashtable, if it is present */ public void delete(int value){ if(positiv(value)){ long key = ((a * value) % n) % m; ht.get(key).remove((Object) value); // if not with Object typecasting, // program will "see" the value (int) as an index // (better solution ?) } } /** * print out the hashtable */ public void print(){ for(int key = 0; key < m; key++){ System.out.print(key + " "); // output index if(ht.get(key) != null){ for(int i = 0; i < ht.get(key).size(); i++){ System.out.print(ht.get(key).get(i) + " "); } } System.out.println(); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 134.93.102.77
PsMonkey:為什麼突然變成 int 11/28 00:16
miyabichan:啊對不起, 現在才看到..因為寫完以後才看到作業要求 11/28 00:18
miyabichan:index 用 long, 結果沒有全改到 orz 11/28 00:19
miyabichan:謝謝,改完就沒問題了,我是白痴 orz 11/28 00:21
adrianshum:我覺得最詭異的是你拿一個hashtable來實作hashtable會 11/28 05:47
adrianshum:不會有點多餘?你不是應該用array 嗎?... 11/28 05:47
用一般 array 我無法 dynamic 的改變 array 長度 一開始我也想用 array 但想破頭都不覺得用 2-d array 的方式比 collection 好
Aztecs:你都用API的了幹嘛還自己寫XDDD 11/28 09:45
Killercat:作業咩 11/28 20:14
miyabichan:我們要寫一個 chained hash table..要是可以用現有的 11/28 20:44
miyabichan:資料結構我也想 QQ 11/28 20:46
sbrhsieh:你應該是搞錯作業的要求了 11/28 21:22
sbrhsieh:這樣子的內容如果可被接受,這作業一點意義都沒有~ 11/28 21:27
這堂課主要是 algorighm.. 我一直覺得要我們寫程式是助教想要整死我們 這個禮拜又要自己寫一個 skip list 程式出來了.. ※ 編輯: miyabichan 來自: 134.93.80.59 (11/30 22:26)
dream1124:我想sb大的意思不是作業本身沒意義, 是你的解法沒意義 12/01 10:12
Killercat:skip list算簡單了 你到後面碰到一顆顆的樹你會懷念他的 12/01 23:56
Killercat:然後最後碰到KD樹就開始生不如死(誤) 12/01 23:57