2012-09-06 52 views
0

我有一個名爲A的類。在這個類中,我有一個String名稱以及一個setter和getter。 我也有正在初始化列表如下:當索引大小爲139時,索引6上的IndexOutOfBoundsException異常

List<A>myList = ArrayList<A>(SomeOtherList); 

現在,當我檢查我的ArrayList的大小,我可以看到列表的大小是139,但是當我試圖讓索引值6,我得到

java.lang.IndexOutOfBoundsException: Index: 6, Size: 6.

但是,如果我嘗試從0打印值 - 138在for循環中我不會例外,

String name = myList.get(6).getName(); // Exception 

for(int i = 0 ; i < 139 ; i++){ 
    System.out.println(myList.get(i).getName()); 
}//will work 

有沒有人遇到過這個問題?

for循環打印所有139名到控制檯 但是當代碼到達get函數我得到的流量異常的線路:

Caused by: java.lang.IndexOutOfBoundsException: Index: 6, Size: 6 
    at java.util.ArrayList.RangeCheck(ArrayList.java:547) 
at java.util.ArrayList.get(ArrayList.java:322) 
at com.icap.dashboard.DashboardPage.getSelectionFromCookie(DashboardPage.java:337) 
at com.icap.dashboard.DashboardPage.addCCYPanelAndChannels(DashboardPage.java:149) 
at com.icap.dashboard.DashboardPage.<init>(DashboardPage.java:107) 
... 52 more 

我編譯使用maven我的項目中初始化的的ArrayList是一個集合Nanes

+2

'java.lang.IndexOutOfBoundsException:Index:6,Size:6' => myList的大小是6.您可以在行之前包含一個'System.out.println(myList.size());'你在哪裏得到例外? – assylias

+2

你應該使用調試器。 – UmNyobe

+4

在達到for循環之前,正在拋出異常並終止執行,因此您錯誤地認爲您沒有收到異常。 – Vulcan

回答

1

這工作:

import java.util.*; 

public class StackOverflow { 

    public static void main(String[] args) { 
     List<A> SomeOtherList = new ArrayList<A>(); 
     for(int i = 0; i < 139; i++) { 
      SomeOtherList.add(new A().setName(String.valueOf(i))); 
     } 
     List<A> myList = new ArrayList<A>(SomeOtherList); 

     System.out.println("random access: " + myList.get(6).getName()); 

     for(int i = 0 ; i < myList.size() ; i++){ 
      System.out.println(myList.get(i).getName()); 
     } 

    } 

    public static class A { 
     String name; 

     public A setName(String theName) { this.name = theName; return(this); } 
     public String getName() { return(this.name); } 
    } 
} 

嘗試使用與您的數據該工作示例。

+0

感謝這是java測試,感謝所有的問題 –

0

錯誤消息說明了自己:您試圖獲取僅包含6個元素的數組的元素6。而且,由於數組索引從0開始,最高可能的索引,你可以要求沒有得到一個異常5.

你的代碼和說明:

String name = myList.get(6).getName(); // Exception 

for(int i = 0 ; i < 139 ; i++){ 
    System.out.println(myList.get(i).getName()); 
}//will work 

是根本不可能的,因爲調用

myList.get(6).getName(); 

將在for循環內進行。對於您所描述的可能的情況,myList在這兩種情況下必須不同。

相關問題