我从学生的ArrayList中删除一个Student对象,这是我的代码,下面是Student.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package corejava.list; /** * * @author Rahul */ public class Student { private int id; private String name; public Student(int id,String name){ this.id = id; this.name = name; } public Student(int id){ this.id = id; } @Override public int hashCode(){ return this.getId() * 37; } @Override public String toString(){ StringBuffer strb = new StringBuffer(); strb.append("\tID : ").append(this.getId()).append(", NAME : ").append(this.getName()); return strb.toString(); } @Override public boolean equals(Object studentOne){ Student student = (Student) studentOne; boolean flag = false; if(this.getId() == student.getId()){ flag = true; } return flag; } /** * @return the id */ public int getId() { return id; } /** * @return the name */ public String getName() { return name; } }
这是我的Class有一个主方法,
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package corejava.list; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * * @author Rahul */ public class RemoveList { public static void main(String [] args){ ListstudentList = null; try{ studentList = new ArrayList (){{ add(new Student(12,"Tom")); add(new Student(14, "Jack")); add(new Student(15, "Julean")); add(new Student(16, "Doughlas")); add(new Student(17, "Bathsheba")); }}; for(Iterator itr = studentList.iterator(); itr.hasNext();){ System.out.println(itr.next()); } System.out.println(studentList.remove(new Student(12))); for(Iterator itr = studentList.iterator(); itr.hasNext();){ System.out.println(itr.next()); } }catch(Exception e){ e.printStackTrace(); } } }
现在我的问题是,可以安全地从ArrayList中删除一个项目,就像我在上面的代码中所做的那样,
hashCode()在从Collection中删除Student对象方面起作用,
我们有更好的方法,
hashCode()在从Collection中删除Student对象方面起作用,
号equals()
方法起作用.
例如,只需查看ArrayList remove()
方法的源代码即可
>public boolean remove(Object o) { 440 if (o == null) { 441 for (int index = 0; index < size; index++) 442 if (elementData[index] == null) { 443 fastRemove(index); 444 return true; 445 } 446 } else { 447 for (int index = 0; index < size; index++) 448 if (o.equals(elementData[index])) { //here 449 fastRemove(index); 450 return true; 451 } 452 } 453 return false; 454 }
是否可以安全地从数组列表中删除项目,就像我在上面的代码中所做的那样.
这个安全 取决于你的Equal定义Student
,因为你告诉Id是否相等,那么Student等于它是安全的(不是讨论线程).