package com.jenthor;
import java.util.*;
/*
* |---Set: 元素是无序的(存入和取出的顺序不一定一致),元素不可以重复
* |---HashSet:底层数 据结构是哈希表
* |---TreeSet
* Set集合的功能和Collection的功能是一致的。
*
*
*
* 往HashSet集合中存入自定对象
* 姓名和年龄相同为同一个人,(重复元素)
*/
public class HashSetDemo {
public static void main(String[] args) {
/*
* Demo d1 = new Demo(); Demo d2 = new Demo();
*
* System.out.println(d1); System.out.println(d2);
*/
/*
* HashSet hs=new HashSet(); hs.add("java01"); hs.add("java02");
* hs.add("java03"); hs.add("java04"); hs.add("java03");
* //System.out.println(hs.add("java04")); add方法的放回是boolean型
*
* Iterator in=hs.iterator(); while(in.hasNext()){
* System.out.println(in.next());
*/
HashSet hs = new HashSet();
hs.add(new Person("a1", 9));
hs.add(new Person("a1", 10));
hs.add(new Person("a3", 13));
hs.add(new Person("a4", 14));
hs.add(new Person("a3", 13));
Iterator it = hs.iterator();
while (it.hasNext()) {
Person p = (Person) it.next();
System.out.println(p.getName() + ".." + p.getAge());
}
}
}
class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAget(int age) {
this.age = age;
}
public int hashCode() {
return name.hashCode()+age*23;
}
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
Person p = (Person) obj;
System.out.println(this.name+"....."+p.name);
return (this.name.equals(p.name) && this.age == p.age);
}
}
hashSet笔记
最新推荐文章于 2023-10-30 13:49:30 发布