import java.util.ArrayList;
import java.util.Iterator;
/*
* Collection
* -----| List 实现List接口的集合类,其对象中的元素是有序且可重复
* ---------| ArrayList List接口实现类 特点是维护了一个ArrayList数组实现的,特点:查询快,增删慢;因为数组的地址是连续的,
* 所以查询速度快,而增删需要新建数组拷贝原值,特别是数据量极大的时候,增删就会非常之慢。如果增删比较少,查询比较多久使用
* ArrayLIst类
* ---------| LinkList List接口实现类
* ---------| Vector List接口实现类
* -----| Set 实现Set接口的集合类,其对象中的元素是无序且不可重复
*
* List接口的实现类:
* ArrayList 特有方法
* ensureCapacity() 指定容量,一般用带参的构造方法去指定
* trimToSize() 裁剪,将容量裁剪至最少,一般也不适用.
*
* 构造方法: ArrayList() 无参构造方法,构造一个容量为10的空集合对象
* ArrayList的内部维护了一个Object的对象数组,使用无参的构造函数创建对象时,默认的容量是10,
* 当容量不够用的时候,长度自动增长0.5倍.
*
*/
//定义人类
class Person{
String name; //姓名
int id; //ID号
public Person(){}
public Person(int id, String name){
this.id = id;
this.name = name;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.id;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
Person p = (Person)obj;
return this.id == p.id;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "{" + this.id +"," + this.name +"}";
}
}
public class Demo3 {
public static void main(String[] args){
//使用迭代器去重
ArrayList al = new ArrayList();
al.add(new Person(100,"张山"));
al.add(new Person(100,"李四"));
al.add(new Person(101, "王五"));
al.add(new Person(101, "王五"));
al.add(new Person(102, "李六"));
al.add(new Person(102, "李六"));
al.add(new Person(102, "李六"));
al = distinct(al);
System.out.println(al);
}
public static ArrayList distinct(ArrayList al){
ArrayList temp = new ArrayList();
Iterator iter = al.iterator();
Person tp = new Person();
while(iter.hasNext()){
tp = (Person)iter.next();
if(temp.contains(tp)){
continue;
}
else{
temp.add(tp);
}
}
return temp;
}
}