大多數時我們要將自訂的對象存入到集合中,在操作自訂對象時常會遇到的問題。
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);