删除数组元素时出错

时间:2013-04-24 16:19:18

标签: java arraylist

我有新的arraylist,1个arraylist,已经插入了10个客户。我正在运行一个循环,从arraylist中挑选一个随机客户并将其添加到第二个arraylist中。但是,当我将客户插入第二个arraylist时,我得到重复。因此,当将客户添加到第二个arraylist之后循环运行时,它将从第一个arraylist中删除它。

然而,当它运行时,我收到一个错误:Intervals error: java.lang.IndexOutOfBoundsException: Index: 7, Size: 7

ArrayList<String> customer = new ArrayList<String>(Arrays.asList(list));

int customerlist = customer.size();

while (line.isEmpty())
        {
            for (int x = 0; x < customerlist; x++ )
            {
                try
                {
                    Thread.sleep(intervals * 1000);   //Sleep method to hold the arrival time by 1-2 seconds. 
                    int cus = (int) (Math.random() * customerlist);   //Random customer is picked here. 
                    String new_cus = customer.get(cus);   //New customer object is created ere.
                    line.add(new_cus);   //Customer objects are added to the empty LinkedList queue.
                    customer.remove(cus);

                    //For loop statement to outputting the queue.
                    for (String s : line)
                    {
                        System.out.print("[" + s.toString() + " " + "]"); //Outputting each customer and using the ".name" method so customers are readable.
                    }
                    //Outputting the whole queue and stating who has joined the queue.
                    System.out.println("\n" + "The queue has " + line.size() + " customers so far" + "\n" + 
                    new_cus.toString() + " Has Joined the Queue " + " <=== WAITING" + "\n");
                }
                catch(Exception e)   //ERROR handler for sleep method.
                {
                    System.out.println("Intervals error: " + e);   //Outputting the ERROR message.
                    System.exit(0);   //If ERROR found exit system.
                }

            }
        }

3 个答案:

答案 0 :(得分:1)

您正在从正在迭代的数组中删除,但没有相应地更新条件。

变化:

for (int x = 0; x < customerlist; x++)

for (int x = 0; x < customer.size(); x++)

(或者更好的是,在底层ArrayList上使用迭代器,以便您可以使用Iterator.remove()函数安全删除。)

同时更改行:

int cus = (int) (Math.random() * customerlist);

int cus = (int) (Math.random() * customer.size());

答案 1 :(得分:1)

这是问题所在:

int cus = (int) (Math.random() * customerlist); 

对于第一次迭代,这很好(尽管不像调用Random.nextInt那样干净) - 但之后,customer.size()已经改变(因为元素已被删除)但customerlist仍然是相同。所以在下一次迭代中,你选择了一个错误范围的元素。

说实话,你最好只使用Collections.shuffle()来移动原始列表 - 这就是你想要的结果,对吗?

答案 2 :(得分:1)

添加

customerlist--;

之后

customer.remove(cus);

另外,你可以改变

for (int x = 0; x < customerlist; x++)

通过

for (int x = 0; x < customer.size(); x++)

但我认为在每个循环中对.size函数的调用比局部变量使用更多的资源。