日期:2014-05-20 浏览次数:20684 次
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--;
}