当我尝试删除元素时出现错误,我已经在图像部分上传了错误。 有什么帮助要解决的吗? 任何其他方法可以使代码修复并顺利运行,并且在删除中间元素而不是第一个或第二个元素时它可以工作重复问题,使用迭代器修复。哈索夫堆叠溢出 .都很好
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");
}
}
}
在迭代集合时,需要使用迭代器安全地从集合中删除集合。
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;
}