Linkedlist删除方法错误

时间:2018-04-18 19:17:59

标签: java arrays linked-list

当我尝试删除元素时出现错误,我已将错误上传到图像部分。任何帮助修复?任何其他方式来修复和平稳工作的代码,它删除中间元素而不是第一个或第二个 重复问题,使用迭代器修复。 hatsooff堆栈溢出。 好的

import java.util.*;

public class EarthquakeList {
private ArrayList<EarthquakeNode> records;

public EarthquakeList() {
   records = new ArrayList<EarthquakeNode>();

}

public boolean isempty() {
      return true;
}


public void add(String EarthquakeLo,String EarthquakeDt, double EarthquakeSgth, int EarthquakeDu) {
   EarthquakeNode en = new EarthquakeNode(EarthquakeLo, EarthquakeDt, EarthquakeSgth, EarthquakeDu);
   records.add(en);
}


public boolean remove(String EarthquakeLo,String EarthquakeDt) {
   boolean flag= false;
   for(EarthquakeNode earthquake: records)
   {
       if(earthquake.getLocation().equalsIgnoreCase(EarthquakeLo))
       {
           if(earthquake.getDate().equals(EarthquakeDt))
           {
               records.remove(earthquake);
               flag=true;

           }
       }
   }
   return flag;
 }


 public EarthquakeNode search(String EarthquakeLo,String EarthquakeDt) {
   EarthquakeNode node= null;
   for(EarthquakeNode earthquake: records)
   {
       if(earthquake.getLocation().equalsIgnoreCase(EarthquakeLo))
       {
           if(earthquake.getDate().equals(EarthquakeDt))
           {

               node=earthquake;
           }
       }
   }
   return node;
}


public boolean clear() {

   int count=records.size();
   for(EarthquakeNode earthquake: records)
   {
       count=count-1;
       records.remove(earthquake);



   }
   if(count==0)
   {
   System.out.println("already empty");
   return false;}

   else 
   System.out.println("every thing is removed");
   return true;
}


public boolean isempty(String EarthquakeLo,String EarthquakeDt) {
   boolean flag= false;
   for(EarthquakeNode earthquake: records)
   {
       if(earthquake.getLocation().equalsIgnoreCase(EarthquakeLo))
       {
           if(earthquake.getDate().equals(EarthquakeDt))
           {
               flag=true;
           }
       }
   }
   return flag;
}


public void print() {
   for(EarthquakeNode earthquake: records)
   {
       System.out.println( earthquake.getLocation() +" - "
              + earthquake.getDate()+ " - "
               + earthquake.getStrength() + " on rector scale"+
               "-" + earthquake.getDuration() + "mins");
   }

}


}

1 个答案:

答案 0 :(得分:0)

您需要使用迭代器在迭代时安全地从集合中删除。

public boolean remove(String earthquakeLo, String earthquakeDt) {
   boolean flag= false;
   Iterator<EarthquakeNode> iterator = records.iterator();
   while(iterator.hasNext()) {
      EarthquakeNode earthquake = iterator.next();
      if(earthquake.getLocation().equalsIgnoreCase(earthquakeLo)) {
           if(earthquake.getDate().equals(earthquakeDt)) {
              iterator.remove();
              flag=true;
           }
      }
   }
   return flag;
 }