您的位置:首页 > 其它

Collection & set

2015-07-26 23:03 197 查看
package test;

import java.util.HashSet;
import java.util.Iterator;

public class HashDemo {

/**
* |--set :元素是无序的(存入和取出的顺序不一定一致),元素不可以重复
*      |--HashSet:底层数据结构是哈希表
*          HashSet是如何保证元素唯一性的呢?
*          通过元素的两个方法,hashCode和equals来完成
*          如果元素的hashCode值相同,才会判断equals是否为true
*          如果元素的hashCode值不同,不会调用equals
*          对于判断元素是否存在,以及删除等操作,依赖的方法是元素
的hashCode(先)和equals(后)方法
*         (ArrayList 依赖的是equals方法)
*      |--TreeSet:
*/
public static void main(String[] args) {

HashSet hs = new HashSet();
sop(hs.add(new Person("a1","11")));//true  add方法返回类型是
boolean
sop(hs.add(new Person("a2","12")));//true
sop(hs.add(new Person("a3","13")));//true

Iterator it =hs.iterator();

while(it.hasNext()){
Person p =(Person)it.next();
sop(p.getName()+"||"+p.getAge());
}
/*
a1--hashcode--30561568
true
a2--hashcode--30571569
true
a3--hashcode--30581570
true
a2--hashcode--30571569
a2|euqals|12
false
a3||13
a1||11
a2||12
*/

sop(hs.contains(new Person("a1","11")));
/*
a1--hashcode--30561568
a1|euqals|11
true
*/
sop(hs.remove(new Person("a2", "12")));
/*
a2--hashcode--30571569
a2|euqals|12
true
*/
}

public static void sop (Object  obj){
System.out.println(obj);
}

}


class Person {

private String name;
private String age;
Person(String name,String age){
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}

/**对象复写hashcode和俄equals方法*/

public boolean equals(Object obj){
if(!(obj instanceof Person)){
return false;
}
Person p =(Person)obj;
System.out.println(this.name+"|euqals|"+this.age);
return this.name.equals(p.name);
}

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