0

ArrayList と for ループを使用して、文字列一致 "Meg" を削除しようとしています。これまでのところ、以下のコードを作成しましたが、なぜ機能しないのかわかりません。while問題は以下のループにあると思います

while((customerName.get(i)).equals("Meg"))
{
  customerName.remove(i);
}

前もって感謝します。

完全なコードは次のとおりです。

import java.util.ArrayList;
public class CustomerLister2
{
  public static void main(String[] args)
  {
    ArrayList<String> customerName = new ArrayList<String>(); 
    customerName.add("Chris");
    customerName.add("Lois");
    customerName.add("Meg");
    customerName.add("Peter");
    customerName.add("Stewie");
    customerName.add(3, "Meg");
    customerName.add(4, "Brian");

    int currentSize = customerName.size();

    for(int i = 0; i < currentSize - 1; i++)
    {

      while((customerName.get(i)).equals("Meg"))
      {
        customerName.remove(i);
      }
    }
    for(String newStr: customerName)
    {
      System.out.println(newStr);
    }
  }
}
4

4 に答える 4

2

次のように変更します

for(int i = 0; i < currentSize; i++)
{
  if((customerName.get(i)).equals("Meg"))
  {
    customerName.remove(i);
    i--;  //because a new element may be at i now
    currentSize = customerName.size(); //size has changed
  }
}
于 2013-03-09T09:30:58.987 に答える
1

または、for ループを使用する必要がない場合:

   public static void main(String[] args) {

        ArrayList<String> customerName = new ArrayList<String>();
        customerName.add("Chris");
        customerName.add("Lois");
        customerName.add("Meg");
        customerName.add("Peter");
        customerName.add("Stewie");
        customerName.add(3, "Meg");
        customerName.add(4, "Brian");

        while (customerName.remove("Meg")) {}

        for (String s : customerName) {
            System.out.println(s);
        }
    }
于 2013-03-09T09:38:01.573 に答える
0

イテレータを使用しますcustomerName.iterator()(iterator()は非静的メソッドです)イテレータはリストのカウント変更を処理します。forループを使用する場合、リストのカウント変更の処理を忘れる可能性があります。

Iterator<String> itr= customerName.iterator();
while(itr.hasNext())
{
    if(itr.next().equals("Meg")){
        itr.remove();
    }
}

イテレータにも欠点があります。2つのスレッドが同じリストオブジェクトに同時にアクセスしている場合は機能しません。元。1つのスレッドが読み取りを行っており、別のスレッドがリストから要素を削除しているため、並行シナリオでjava.util.ConcurrentModificationException.使用するのに適しています。Vector

それでも同じforループを使用する場合は、次のコード行を追加します。

int currentSize = customerName.size();

for(int i = 0; i < currentSize; i++)
{

  while((customerName.get(i)).equals("Meg"))
  {
    customerName.remove(i);
    currentSize = customerName.size(); //add this line to avoid run-time exception.
  }
}
于 2013-03-09T10:55:48.460 に答える
0

これはあなたを助けるでしょう

System.out.println("Customer Name (including Meg)"+customerName);
for(int i=0; i<customerName.size(); i++)
{
  String s = customerName.get(i);
  if(s.equals("Meg"))
  {
     customerName.remove(i);
     i--;
  }
}
System.out.println("Customer Name (excluding Meg)"+customerName);
于 2013-03-09T09:43:22.653 に答える