为什么我的arrayList选择已删除的项目?

时间:2017-03-26 14:05:59

标签: java arraylist

我有一个arrayList,有大约80个对象,我试图随机选择一个对象,将其分配给另一个对象,从数组列表中删除它然后返回所选对象。相反,我将返回已被删除的对象。

这是我的代码:

while (!ballStorage.isEmpty()) {
    SecureRandom rnd = new SecureRandom();

    int arraySize = ballStorage.size();//this is 80
    for (int j = 80; j >= 0; j--) {
        while (arraySize > 0) {

            int i = rnd.nextInt(arraySize);

            ballSelected = ballStorage.get(i);
            ballStorage.remove(i);
            ballStorage.trimToSize();
            arraySize--;

            //debugging println's
            System.out.print(ballStorage);
            System.out.println("random number generated is: " + i);
            System.out.println("ball selected is: " +ballSelected);
            System.out.println("Array size is: " + arraySize);

            return ballSelected;
        }

    }
}
return ballSelected;

//output:45W,[62Bl,, 74Bl,]random number generated is: 2
  ball selected is: 16W,
  Array size is: 2
  16W,[62Bl,]random number generated is: 1
  ball selected is: 74Bl,
  Array size is: 1
  74Bl,[]random number generated is: 0
  ball selected is: 62Bl,
  Array size is: 0

1 个答案:

答案 0 :(得分:0)

 while (!ballStorage.isEmpty()) {

        SecureRandom rnd = new SecureRandom();


        int i = rnd.nextInt(ballStorage.size());

        ballSelected = ballStorage.get(i);
        ballStorage.remove(i);
        ballStorage.trimToSize();





         System.out.print(ballStorage);
         System.out.println("random number generated is: " + i);
         System.out.println("ball selected is: " +ballSelected);
         System.out.println("Array size is: " + arraySize);

  }


    return ballSelected; 

我无法理解为什么你会回到循环中。这就是为什么你的原因 循环执行1次。

但我想你每次都想要返回BallSelected:

class BallStorage implements Iterator<Ball>, Iterable<Ball> {

     private int size;
     private Random random;
     private ArrayList<Ball> balls;


     public BallStorage() {
        this.size = 0;
        this.balls = new ArrayList<>();
        this.random = new Random();
     }

     public void add(Ball ball) {
       this.size++;
       balls.add(ball);
     } 

     Ball next() {

        Ball b = balls.get(random.nextInt(size));
        balls.remove(b);
        this.size--;
    return b;
     }

     boolean hasNext() {
        return size > 0;
     }

     Iterator<Ball> iterator() {
        return this;
     }

     public static void main(String[] args) {
         //Create Balls and add them in ballStorage object

         for(Ball ball: ballStorage)
             System.out.println("ball selected is: " +ball);
     }

}