ArrayList和HashSet如何去除重複元素
阿新 • • 發佈:2019-02-06
1. ArrayList去除重複元素
利用contains()方法,其內部呼叫的還是equals()方法,需要重寫equals(),自己定義元素相同的規則
import java.util.*;
class ArrayListDemo2 {
public static void main(String[] args) {
ArrayList a = new ArrayList();
ArrayList a2 = new ArrayList();
a.add(new People("張三",3));
a.add(new People("李四",4));
a.add(new People("李四",4));
a.add(new People("王五",5));
System.out.println(a); // 此處列印物件地址值
// 兩種方法取list當中的元素,for和iterator
// contains()方法底層呼叫equals(),remove()
for (int i = 0; i < a.size() ; i++ ) {
Object obj = a.get(i);
if (!a2.contains(obj)) {
a2.add(obj);
}
}
Iterator i = a2.iterator();
while(i.hasNext()) {
People p = (People) i.next();
System.out.println(p.getName() + "..." + p.getAge());
}
}
}
class People {
private String name;
private int age;
People (String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge(){
return this.age;
}
// 要比較兩個人相不相同需要重寫equals()方法來比較姓名年齡
public boolean equals(Object obj) {
if (!(obj instanceof People)) {
return false;
} else {
People p = (People)obj;
return this.name.equals(p.name) && this.age == p.age
}
}
}
2. HashSet元素唯一性
當新增一個元素時,首先呼叫hashCode()方法講該元素和集合中存在的元素進行hashCode判斷,如果存在兩個元素hashCode相同,再呼叫equals()方法進行判斷兩個元素是否是相同的物件。如果都相同,則新元素無法被新增。
所以一般情況下,當我們需要用到HashSet時候,必須重寫hashCode()和equals()兩個方法
import java.util.*;
class HashSetDemo {
public static void main(String[] args) {
HashSet hs = new HashSet();
hs.add(new People("張三",3));
hs.add(new People("李四",4));
hs.add(new People("王五",5));
hs.add(new People("李四",4));
System.out.println(hs);
Iterator i = hs.iterator();
while (i.hasNext()) {
People p = (People)i.next();
System.out.println(p.getName() + " ...." + p.getAge());
}
}
}
class People {
private String name;
private int age;
People (String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge(){
return this.age;
}
public int hashCode() {
System.out.println(this.name + "...hashCode");
return this.name.hashCode() + this.age*19; // 自定義物件的hashCode,儘量保證不出現重複
}
public boolean equals(Object obj) {
if (!(obj instanceof People)) {
return false;
} else {
People p = (People)obj;
System.out.println(this.name + "....equals..." + p.name);
return this.name.equals(p.name) && this.age == p.age
}
}
}