您的位置:首页 > 其它

集合框架_06_HashSet集合

2016-08-20 17:55 197 查看
/*
|--Set:元素是无序(存入和取出的顺序不一定一致),元素不可以重复。、
|--HashSet:底层数据结构是哈希表。是线程不安全的。不同步。
HashSet是如何保证元素唯一性的呢?
是通过元素的两个方法,hashCode和equals来完成。
如果元素的HashCode值相同,才会判断equals是否为true。
如果元素的hashcode值不同,不会调用equals。

注意,对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hashcode和equals方法。
|--TreeSet:

Set集合的功能和Collection是一致的。
*/
class HashSetDemo
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
HashSet hs = new HashSet();
sop(hs.add("java01"));
sop(hs.add("java01"));
hs.add("java02");
hs.add("java03");
hs.add("java03");
hs.add("java04");
Iterator it = hs.iterator();
while(it.hasNext())
{
sop(it.next());
}
}
}


HashSet存放自定义元素

/*
往hashSet集合中存入自定对象
姓名和年龄相同为同一个人,重复元素。
*/
class HashSetTest {
public static void sop(Object obj) {
System.out.println(obj);
}

public static void main(String[] args) {
HashSet hs = new HashSet();

hs.add(new Person("a1", 11));
hs.add(new Person("a2", 12));
hs.add(new Person("a3", 13));
// hs.add(new Person("a2",12));
// hs.add(new Person("a4",14));

// sop("a1:"+hs.contains(new Person("a2",12)));

// hs.remove(new Person("a4",13));

Iterator it = hs.iterator();

while (it.hasNext()) {
Person p = (Person) it.next();
sop(p.getName() + "::" + p.getAge());
}
}
}

class HashSetPerson {
private String name;
private int age;

HashSetPerson(String name, int age) {
this.name = name;
this.age = age;
}

public int hashCode() {
System.out.println(this.name + "....hashCode");
return name.hashCode() + age * 37;
}

public boolean equals(Object obj) {

if (!(obj instanceof Person))
return false;

HashSetPerson p = (HashSetPerson) obj;
System.out.println(this.name + "...equals.." + p.name);

return this.name.equals(p.name) && this.age == p.age;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: