2015-12-08 38 views
-1

所以,如果這是我的課程:如何從Arraylist中刪除隨機對象?

我的問題是,在步驟()函數的條件2,我該如何從數組列表中刪除該對象?我不確定,因爲隨機選擇隨機函數

import java.util.Random; 

public class test{ 

private ArrayList<list> holder; 


    public class(){ 

    int i = 0; 

     holder = new ArrayList<Student>(); 

     for (i=0;i<S;i++){ 

      holder.add(new holder(i, library)); 
     } 
} 


public void step(){ 

box = students.get(random.nextInt(holder.size())); 

if (condition 1){ 

do this 

} else if (condition 2){ 

** remove the random object from arraylist (how?)** 

} 

} 

回答

0

使用您導入的java.util.Random隨機生成要刪除的值。

所以你可以做Radom rand = new Random();

rand.nextInt(<MAX_TO_GENERATE>) + <MIN_TO_GENERATE>;

MAX_TO_GENERATE是價值,你想讓它上去(請記住,隨機是排他性的,所以如果你做100只會上升到99),然後設置MIN_TO_GENERATE到最低值,你'它喜歡它產生。

看來您正在將人員添加到ArrayList,並且此列表可能包含5,000個人,因此可能有一個變量來保存學生人數。看起來你打算和我一起做這件事,但我並不完全確定。

編輯: 一旦你生成一個值,將其分配給一個變量,例如

int randomNum = rand.nextInt(<MAX_TO_GENERATE>) + <MIN_TO_GENERATE>;

,然後你可以做一個if語句刪除它,如:

if(holder.get(randomNum) != null) { holder.remove(randomNum); }

0

方法一,只需使您的索引變量。

public void step(){ 
    int index=random.nextInt(holder.size()); 
    box = students.get(index); 
    if (condition 1){ 
     //do this - this is a comment 
    } 
    else if (condition 2){ 
     students.remove(index); 
    } 
} 

方法2,如果你的類的對象是不是int類型或整型:

public void step(){ 
    box = students.get(random.nextInt(holder.size())); 
    if (condition 1){ 
     //do this - this is a comment 
    } 
    else if (condition 2){ 
     students.remove(box); 
    } 
} 

希望這應該解決這個問題。此外,JavaDocs是你的朋友,引用他們看哪些方法做什麼以及如何調用它們。