Re: [問題] Hashtable<String,Integer> 取數字
※ 引述《daeam (。.。)》之銘言:
: 首先 資料存在Hashtable中
: Hashtable<String,Integer> table = new Hashtable<String,Integer>();
: 我要依序取出Hashtable中的key與value存到資料庫
: 然後就
: Set<Entry<String, Integer>> t = table.entrySet();
: Iterator it = t.iterator();
: while (it.hasNext()){
: Entry entry = (Entry) it.next();
: String word = (String) entry.getKey();
: int times = (int)entry.getValue(); //----> Object無法轉換成int
: // float tf = (float)times/numToken; // ---> 尷尬 Orz
: .....
: }
Set<Entry<String, Integer>> t = table.entrySet();
既然用 JDK5 就簡單一點這樣寫吧:
for (Entry<String, Integer> entry : t) {
String word = entry.getKey();
int times = entry.getValue();
}
真的要用 Iterator 的話,也要加 type info 才行吧
大概是
Iterator<Entry<String,Integer>> itr = t.iterator();
while (itr.hasNext()) {
Entry<String Integer> entry = itr.next();
String word = entry.getKey();
....
}
用 eclipse 就會提醒你忘了加 generics 的 type info
: 我不知道該怎麼寫 才能依序取出我在Hashtable中的資料
: 並分別給予 String/int 型態
: 因為我Hashtable中的value是我要拿來做運算用的 所以不能是object
: 只想到很蠢的方式 : 拿出word後再反查hashtable 去getValue ...
: 不知道有沒有比較好的寫法呢?
: 謝謝解答 :)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.79.101.215
推
04/23 17:10, , 1F
04/23 17:10, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):