写过的类似代码:
/** * 2018年5月20日上午9:54:02 */ package com.test; import java.util.ArrayList; import java.util.List; /** * @author xinwenfeng * */ public class TestListRemove { /** * @param args */ public static void main(String[] args) { List<Integer> ageList = new ArrayList<>(); Student stu1 = new Student(7, "Tom"); Student stu2 = new Student(6, "Jerry"); Student stu3 = new Student(4, "Mordecai"); Student stu4 = new Student(5, "Lilith"); Student stu5 = new Student(8, "Roland"); Student stu6 = new Student(9, "Brick"); ageList.add(stu1.getAge()); ageList.add(stu2.getAge()); ageList.add(stu3.getAge()); ageList.add(stu4.getAge()); ageList.add(stu5.getAge()); ageList.add(stu6.getAge()); System.out.println(ageList); //删掉Lilith,age=5 ageList.remove(stu4.getAge()); System.out.println(ageList);//发现删掉的是stu6 //删掉Roleand,age=8 // ageList.remove(stu5.getAge());//Exception:java.lang.IndexOutOfBoundsException: Index: 8, Size: 5 //正确删掉Jerry ageList.remove((Integer)stu2.getAge()); System.out.println(ageList); } } class Student{ private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; public Student(int age, String name) { super(); this.age = age; this.name = name; } @Override public String toString() { return age+":"+name; } }
结果:
发生这样的bug经常要找很久,因为自认为list是按照age塞进去的,按照age删肯定没问题,通常也不会想到这样的bug而优先去找业务逻辑的bug,出现这种问题的原因就在list的remove方法有两个:
Student的age属性是int而不是Integer,所以remove(stu.getAge())的时候传递的是int,调用的是remove(int index)方法,根据索引删除,这样造成两种结果:删错(删掉Lilith)、异常(删掉Roland)。要正常删除应把age转型成Integer对象,调用remove(Object)方法而不是remove(int)。