import java.util.ArrayList;
import java.util.Iterator;
/*
* Collection
* -----| List 實(shí)現(xiàn)List接口的集合類,其對(duì)象中的元素是有序且可重復(fù)
* ---------| ArrayList List接口實(shí)現(xiàn)類 特點(diǎn)是維護(hù)了一個(gè)ArrayList數(shù)組實(shí)現(xiàn)的,特點(diǎn):查詢快,增刪慢;因?yàn)閿?shù)組的地址是連續(xù)的,
* 所以查詢速度快,而增刪需要新建數(shù)組拷貝原值,特別是數(shù)據(jù)量極大的時(shí)候,增刪就會(huì)非常之慢。如果增刪比較少,查詢比較多久使用
* ArrayLIst類
* ---------| LinkList? List接口實(shí)現(xiàn)類
* ---------| Vector List接口實(shí)現(xiàn)類
* -----| Set? 實(shí)現(xiàn)Set接口的集合類,其對(duì)象中的元素是無序且不可重復(fù)
*
* List接口的實(shí)現(xiàn)類:
* ArrayList 特有方法
* ensureCapacity() 指定容量,一般用帶參的構(gòu)造方法去指定
* trimToSize() 裁剪,將容量裁剪至最少,一般也不適用.
*
* 構(gòu)造方法: ArrayList() 無參構(gòu)造方法,構(gòu)造一個(gè)容量為10的空集合對(duì)象
* ArrayList的內(nèi)部維護(hù)了一個(gè)Object的對(duì)象數(shù)組,使用無參的構(gòu)造函數(shù)創(chuàng)建對(duì)象時(shí),默認(rèn)的容量是10,
* 當(dāng)容量不夠用的時(shí)候,長(zhǎng)度自動(dòng)增長(zhǎng)0.5倍.
*
*/
//定義人類
class Person{
String name; //姓名
int id; //ID號(hào)
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;
}
}