import java.util.*;
public class ArrayListDemo{
public static void main(String args[]){
hashSet();
}
//hashset判断加入重复
public static void hashSet(){
HashSet hs = new HashSet();
/*
* HashSet集合数据结构是哈希表,所以存储元素的时候,
* 使用的元素的hashCode方法来确定位置,如果位置相同,在通过元素的equals来确定是否相同。
*
*/
hs.add(new Person("lisi4",24));
hs.add(new Person("lisi7",27));
hs.add(new Person("lisi1",21));
hs.add(new Person("lisi9",29));
hs.add(new Person("lisi7",27));
Iterator it = hs.iterator();
while(it.hasNext()){
Person p = (Person)it.next();
System.out.println(p);
// System.out.println(p.getName()+"...."+p.getAge());
}
}
//list集合去重
public static void listRemoveCommon(){
ArrayList al = new ArrayList();
al.add(new Person("lisi1",21));
al.add(new Person("lisi2",22));
al.add(new Person("lisi3",23));
al.add(new Person("lisi4",24));
al.add(new Person("lisi2",22));
al.add(new Person("lisi3",23));
System.out.println(al);
System.out.println(removeCommon2(al));
}
//去除list中重复值--方法2
public static List removeCommon2(List al){
List list = new ArrayList();
for(Iterator it = al.iterator();it.hasNext();){
Object obj = it.next();
if(!list.contains(obj)){
list.add(obj);
}
}
return list;
}
//去除list中重复值--方法1
public static List removeCommon(List list){
Set set = new HashSet(list);
return new ArrayList(set);
}
}
public class Person
{
private String name;
private Integer age;
public String getName(){
return name;
}
public Integer getAge(){
return age;
}
public Person(String name,Integer age){
this.name = name;
this.age = age;
}
public boolean equals(Object obj){
if(!(obj instanceof Person)){
return false;
}
Person person = (Person)obj;
return this.name.equals(person.getName())&&(this.age.compareTo(person.getAge())==0);
}
public int hashCode(){
return name.hashCode() + age;
}
}