作者tkcn (小安)
看板java
标题Re: [问题] Hashtable<String,Integer> 取数字
时间Thu Apr 22 23:52:00 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
这里拿到的是一个 Object Reference,
但实际指向的物件是 Integer,
所以你可以强制转型成 Integer,
int times = (Integer) entry.getValue(); // 这里还会用到 auto-unboxing 特性
但是,如果你善用了 Generic,指明 Entry 的 Value's Type 是 Integer,
那麽 entry.getValue() 回传的物件就会是 Integer,也就不需要做任何手动的转型了。
--
◤ ◥ ◢ ◣
T$,修好它吧。 ⊙▁⊙─ ─⊙▂⊙ 碰到问题,用SoftICE就对了!
╰ ∕皿﹨ ◥皿◤ ╯
◥█◤◢ ◥ ︶◤
Lee ◤ ︶ ◥◤ ﹨▼∕◥ T$ Chen
MYTHBUGTERS ◥ ◤\◥ by dajidali
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.132.160.117
1F:推 daeam:喔喔! 我都太习惯直接用int 感谢提醒 :) 04/23 13:41