[問題] 請問一個Collection的問題

看板java作者 (tou)時間16年前 (2008/07/02 21:49), 編輯推噓5(503)
留言8則, 5人參與, 最新討論串1/2 (看更多)
import java.util.*; public class ArrayListDemo { public static void main(String[] args) { List lists = new LinkedList(); lists.add("abc"); lists.add(new Integer(3)); lists.add("def"); lists.add(new Integer(3)); System.out.println(lists); Iterator it = lists.iterator(); while(it.hasNext()) { if(it.next() instanceof String) { String str = (String)it.next(); System.out.println(str); } else if(it.next() instanceof Integer) { Integer integer = (Integer)it.next(); System.out.println(integer); } //System.out.println(it.next() instanceof String); //System.out.println(it.next() instanceof Integer); } } } 請問在未用泛型時,利用Iterator照順序取出List內的物件 要使用該物件的功能時必須自己轉型回物件原本的型態 那我用instanceof來一一檢查該物件是否為某個型態再轉型 可是執行時會出現ClassCastException 因為這個範例只有String和Integer物件,我也一一檢查了 請問為什麼在轉型時還是失敗了呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 124.8.52.188

07/02 22:07, , 1F
先在 API 看清楚 next() 的說明吧
07/02 22:07, 1F
※ 編輯: jtorngl 來自: 124.8.52.188 (07/02 22:19)

07/02 22:24, , 2F
在While內我先 Object obj = it.next();
07/02 22:24, 2F

07/02 22:26, , 3F
然後後面的it.next()全改成obj,所以是我亂用it.next() ?
07/02 22:26, 3F

07/02 22:50, , 4F
next()會回傳一個E type的element,這裡的E指的是Object吧
07/02 22:50, 4F

07/02 23:25, , 5F
光字面上的意義 就可以了解那是會往下跳一個element了
07/02 23:25, 5F

07/02 23:27, , 6F
it.haseNext回傳boolean 你可試試看while(true)能看到什麼
07/02 23:27, 6F

07/02 23:51, , 7F
因為你比對的和轉型的是不同的物件
07/02 23:51, 7F

07/03 16:16, , 8F
每it.next() 就會跳到下一個object,你多呼叫太多次
07/03 16:16, 8F
文章代碼(AID): #18QuTGJX (java)
文章代碼(AID): #18QuTGJX (java)