[問題] 找得到內容卻print不出來
這個作業我們要自己實作只能存正整數 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
推
11/28 00:16, , 1F
11/28 00:16, 1F
→
11/28 00:18, , 2F
11/28 00:18, 2F
→
11/28 00:19, , 3F
11/28 00:19, 3F
→
11/28 00:21, , 4F
11/28 00:21, 4F
→
11/28 05:47, , 5F
11/28 05:47, 5F
→
11/28 05:47, , 6F
11/28 05:47, 6F
用一般 array 我無法 dynamic 的改變 array 長度
一開始我也想用 array 但想破頭都不覺得用 2-d array 的方式比 collection 好
→
11/28 09:45, , 7F
11/28 09:45, 7F
→
11/28 20:14, , 8F
11/28 20:14, 8F
→
11/28 20:44, , 9F
11/28 20:44, 9F
→
11/28 20:46, , 10F
11/28 20:46, 10F
→
11/28 21:22, , 11F
11/28 21:22, 11F
→
11/28 21:27, , 12F
11/28 21:27, 12F
這堂課主要是 algorighm.. 我一直覺得要我們寫程式是助教想要整死我們
這個禮拜又要自己寫一個 skip list 程式出來了..
※ 編輯: miyabichan 來自: 134.93.80.59 (11/30 22:26)
→
12/01 10:12, , 13F
12/01 10:12, 13F
→
12/01 23:56, , 14F
12/01 23:56, 14F
→
12/01 23:57, , 15F
12/01 23:57, 15F
java 近期熱門文章
PTT數位生活區 即時熱門文章