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
這裡拿到的是一個 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
推
04/23 13:41, , 1F
04/23 13:41, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):