public static void main(String[] args) {
//添加student对象进list里面
LinkedList list=new LinkedList();
Studentinfo si1 = new Studentinfo("张三", 19);
Studentinfo si2 = new Studentinfo("李四", 18);
Studentinfo si3 = new Studentinfo("王五", 20);
list.add(si1);
list.add(si2);
list.add(si3);
//添加end
//删除集合里面student对象name为李四的元素
for (int i = 0; i < list.size(); i++) {
Studentinfo si = (Studentinfo)list.get(i);
if(si.getName().equals("李四")){
list.remove(si);
}
System.out.println(si.getName()+"\t\t"+si.getAge());
System.out.println(list.size());
}
//出现的问题:我删除张三输出的时候没有了李四,我删除李四输出的时候没有了王五,但我要删除的对象还可以输出
}
控制台输出信息:
张三 19
3
李四 18
2
------解决方案--------------------------------------------------------
- Java code
package cai;import java.util.LinkedList;class Studentinfo { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Studentinfo(String name, int age) { super(); this.name = name; this.age = age; } public Studentinfo() { }}public class Test { public static void main(String[] args) { // 添加student对象进list里面 LinkedList list = new LinkedList(); Studentinfo si1 = new Studentinfo("张三", 19); Studentinfo si2 = new Studentinfo("李四", 18); Studentinfo si3 = new Studentinfo("王五", 20); list.add(si1); list.add(si2); list.add(si3); // 添加end // 删除集合里面student对象name为李四的元素 for (int i = list.size() - 1; i > 0; i--) { Studentinfo si = (Studentinfo) list.get(i); if (si.getName().equals("张三")) { list.remove(si); } System.out.println(si.getName() + "\t\t" + si.getAge()); System.out.println(list.size()); } }}
------解决方案--------------------------------------------------------
for (int i = 0; i < list.size(); i++) 当你remove时list.size()会变小
所以记得 if(si.getName().equals("李四")){
list.remove(si);
加一句 i--;
}