大多数时我们要将自定义的对象存入到集合中,在操作自定义对象时常会遇到的问题。
1. 首先是使用普通for循环遍历对象时,将满足条件的对象删除等操作。
if(26 == list.get(i).getAge())
list.remove(i);
删除后发现结果用仍有年龄为26的对象被保留下来,这是为什么呢?参见下图。是因为在遍历时有的对象没有被判断到。
package com.test.list; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class AddCustomElements { public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); list.add(new Student("zhangsan", 26)); list.add(new Student("lisi", 26)); list.add(new Student("wangwu",30)); list.add(new Student("niuqi", 26)); //如果要将年龄为26的元素删除使用普通for循环和Iterator迭代器有点区别: for(int i = 0; i < list.size(); i++) { if(26 == list.get(i).getAge()) //list.remove(i); //为了避免有漏掉的对象 list.remove(i--); } System.out.println("For: "+list); //使用迭代器就可以将所有满足条件的对象删除 for(Iterator<Student> it = list.iterator(); it.hasNext();) { if(26 == it.next().getAge()) it.remove(); } System.out.println("Iterator: "+list); } } class Student { private String name; 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; } private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String toString() { return name.toString()+", "+ age; } }
2. 如果是同年龄,同名字的Student就看成是同一个对象,要在集合中删除相同元素时,就要复写Student类中的equals()方法。
package com.test.list; import java.util.ArrayList; import java.util.List; public class CustomElements { public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); list.add(new Student("zhangsan", 24)); list.add(new Student("lisi", 29)); list.add(new Student("zhangsan", 24)); list.add(new Student("zhaoliu", 30)); List<Student> tempList = singleElements(list); for(Student stu: tempList) { System.out.println(stu.getName()+", "+stu.getAge()); } } //定义一个方法,将List集合中的重复元素去掉 public static <T> List<T> singleElements(List<T> list) { List<T> tlist = new ArrayList<T>(); if (list == null || list.isEmpty()) { return tlist; } for (T t : list) { if (!tlist.contains(t)) { tlist.add(t); } } return tlist; } } class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = 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; } //如果不复写equals()方法,就不知道什么样的元素是相同的 public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
因为复写了equals()方法,可以使用indexOf(), lastIndexOf()方法等
int index = list.lastIndexOf(new Student("zhangsan", 24)); System.out.println("index = "+ index);