3 回答
TA贡献1811条经验 获得超6个赞
我建议Iterator为此使用 an ,因为在迭代时更改对象的状态时使用List.remove(Object o)can throw 。ConcurrentModificationException
所以Iterator.remove()将是一个安全的赌注。来自Java SE 1.8文档:
迭代器允许调用者在迭代期间以定义明确的语义从底层集合中移除元素。
所以直接从Listusing 中移除一个对象List.remove()会导致不可预知的迭代,并在迭代时抛出ConcurrentModificationException。
如果您不进行迭代,则可以使用 将List.remove(Object o)对象从List.
//Initializes the iterator, checks if next element is present by calling Iterator.hasNext()
for(Iterator<MemberPlayer> itr = memberList.iterator(); itr.hasNext(); ){
m = itr.next(); //The current element of the List
if(m.getFirstName().contains(fName) && m.getLastName().contains(lName)) {
System.out.println();
System.out.println("This MemberPlayer exist:");
System.out.println(fName + " " + lName);
System.out.print("Do you want to remove this MemberPlayer? [yes/no]");
input.nextLine().toUpperCase();
if (input.equals("Yes")) {
itr.remove(); //Removes the current element if the condition is satisfied.
}else{
break;
}
}else {
System.out.println();
System.out.println("This MemberPlayer doesn't exist");
System.out.println();
break;
}
}
TA贡献1966条经验 获得超4个赞
经过反复试验,这最终为我工作。
public void removeMember()throws FileNotFoundException {
System.out.println("Which MemberPlayer are you looking to remove?:");
System.out.print("Input first name: ");
String fName1 = input.nextLine().toUpperCase();
System.out.print("Input last name: ");
String lName2 = input.nextLine().toUpperCase();
for (MemberPlayer m : memberlist){
if (m.getFirstName().equals(fName1) & m.getLastName().equals(lName2)) {
System.out.println();
memberlist.remove(m);
System.out.println("You removed: "+m.getFirstName()+" "+m.getLastName());
System.out.println();
saveMember();
break;
} else {
System.out.println();
System.out.println("This MemberPlayer doesn't exist");
System.out.println();
break;
}
}
}
TA贡献1829条经验 获得超6个赞
您需要使用文档中的List#remove():
布尔删除(对象 o)
如果指定元素存在,则从该列表中删除第一次出现的指定元素(可选操作)。如果此列表不包含该元素,则它不变。更正式地说,删除具有最低索引 i 的元素,使得 (o==null ? get(i)==null : o.equals(get(i))) (如果存在这样的元素)。如果此列表包含指定的元素(或等效地,如果此列表因调用而更改),则返回 true。
另外,这里不需要for-loop。您的方法可以简化为更面向对象的方法:
public void removeMember() {
System.out.println("Which MemberPlayer are you looking for?:");
System.out.print("Input first name: ");
String fName = input.nextLine().toUpperCase();
System.out.print("Input last name: ");
String lName = input.nextLine().toUpperCase();
// create an object with input received
MemberPlayer m = new MemberPlayer(fName, lName);
// use contains of List
if (memberlist.contains(m)) {
memberlist.remove(m);
} else {
System.out.println("This MemberPlayer doesn't exist");
}
}
确保覆盖. .equals()_.hashcode()MemberPlayer
添加回答
举报