[英]How to remove an object from an ArrayList?
我想根據學生姓名從ArrayList中刪除一個對象,每個對象有5個元素。 問題:如何從文本文件中刪除對象。
ArrayList<Student> studentList= new ArrayList<Student>();
Iterator iter = studentList.iterator();
public DVD remove(String removeName) {
while (iter.hasNext()) {
for (Student stu : studentList) {
if (stu .GetName().toUpperCase().contains(removeName.toUpperCase())) {
System.out.println("Found And Removed");
iter.remove();
return stu ;
}
System.out.println("Not Found");
}
}
return null;
}
每個學生都是從文本文件中讀取的。 每行一個元素。
例如:
John Smith
Undergrad
21 years old
2010
2014
Pocahantas
Professor
369 years old
1599
1603
Etc... // new person
etc....
我認為您不需要迭代器:
public Student remove(String removeName) {
for (Student stu : studentList) {
if (stu.getName().toUpperCase().contains(removeName.toUpperCase())) {
System.out.println("Found and Removed");
studentList.remove(stu);
return stu;
}
}
System.out.println("Not Found");
return null;
}
您使用錯誤的迭代器方式; 如果使用外部迭代器進行迭代,則無需for
語句:
while (iter.hasNext()) {
Student stu = iter.next();
if (stu .GetName().toUpperCase().contains(removeName.toUpperCase())) {
System.out.println("Found And Removed");
iter.remove();
return stu ;
}
System.out.println("Not Found");
}
}
如果您以前了解過學生(或其位置),則可以從List
接口簡單地調用remove
方法,但是如果要在遍歷集合時將其刪除,那么大多數Java Collections都會采用外部迭代器。
如果我理解正確,您想刪除與必須從文本文件中刪除的學生姓名相對應的5行。
如果這是您要執行的操作,請參考
這具有刪除單個行的代碼段。 您需要做的就是在遇到要刪除的名稱后立即刪除接下來的5行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.