Re: [問題] Hashtable<String,Integer> 取數字

看板java作者 (小安)時間15年前 (2010/04/22 23:52), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/3 (看更多)
※ 引述《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
喔喔! 我都太習慣直接用int 感謝提醒 :)
04/23 13:41, 1F
文章代碼(AID): #1Bq72Z5G (java)
文章代碼(AID): #1Bq72Z5G (java)