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
}
}
}