作者adrianshum (Alien)
看板java
标题Re: [问题] Hashtable<String,Integer> 取数字
时间Thu Apr 22 23:53:48 2010
※ 引述《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
1F:推 daeam:感谢回答~ 让我观念更清晰了 :) 04/23 17:10