2013-10-16 54 views
0
static ArrayList<Integer> usedArray = new ArrayList<Integer>(); 

public static void arrayContents(){ 

usedArray.add(2, 2); 
usedArray.add(1, 1); 

} 

public static void app(){ 

    Random generator = new Random(); 

    int randomNumber = generator.nextInt(usedArray.size()); 

    System.out.println(usedArray); 

    System.out.println(randomNumber); 


    if(randomNumber == 2){ 
     score(); 
     question2(); 
     usedArray.remove(2); 
     app(); 
    } 

隨着生成從一個ArrayList在Java不含0的隨機數

.add(2, 2) 

我得到一個錯誤:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0 

然而,使用

.add(2) 

0生成作爲數組的一部分,儘管它不是一個值陣列。數組默認情況下總是包含0,並且有什麼方法可以解決這個問題,這樣0就不會產生爲隨機數?

+1

請閱讀類'javadoc在使用之前。 –

+0

爲什麼你使用基於索引的add? .add(index,object)而不是.add(object) –

+0

'ArrayLists'有* 0-based *索引(即)起始索引爲'0',最後一個索引爲'list.size() - 1 '。 – SudoRahul

回答

0

您遇到的問題是您創建一個空的List,輸入new ArrayList<Integer>()

不能使用add(int index, E element)因爲它

Inserts the specified element at the specified position in this list.

您的列表中有長度等於0異常發生。

當您使用add(E e)它。

Appends the specified element to the end of this list.

特德·霍普在評論

The problem is that you cannot insert beyond the current end of the list.

指出,這意味着你可以使用add(int index, E element),只有當指數比情人大小。

此外,當你調用

int random = new Random().nextInt(list.size());

那麼結果是介於0(含)list.size()(獨家)。這意味着你總是會得到一些有效的索引,你不必擔心訂單。

+0

因此0是包容性的,它將始終有被生成的機會? –

+1

列表容量與OP爲什麼會發生異常無關。問題是你不能插入到列表的最後。 –

+0

@TedHopp,感謝這一課。 –

0

在您的代碼中,您已從列表中刪除第二個位置並嘗試更新它。這就是你獲得AIOBE的原因。使用add()或嘗試增加列表大小。

1

您遇到此問題是因爲當您創建數組列表時,它的大小爲零,因此當您調用usedArray.add(2, 2);時,您嘗試使用整數2更新您的數組列表中的第二位;但正如我所說,陣列列表目前沒有2號插槽。除非你有使用.add(index, object)方法只需添加它們通常有原因的,因爲.add(object)

usedArray.add(2, 2); //<-- here you update slot 2, putting Integer 2 in it, there is no slot 2 at this point 

如果這僅僅是你可以使用現有的隨機數的列表;

usedArray.add(1); 
usedArray.add(2); 

現在數字1和2在arraylist中可用。

這些然後可以從該ArrayList隨機取:

int randomNumber = usedArray.get(generator.nextInt(usedArray.size())); 

在這個例子中generator.nextInt(usedArray.size()將產生數字0或1,其將來自該ArrayList分別取1或2

+0

當1或2從arrayList中移除時,只會生成0,因爲arrayList中只有1個項目? –

+0

@leo在arraylist中沒有零,除非你把一個放在那裏 –