HashSet的使用

package test;

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

public class HashSetDemo {
	
	public static void main(String[] args) {
		// TODO 自動生成的方法存根
		HashSet h = new HashSet();
		h.add(new Human(17,"zhangsan"));
		h.add(new Human(17,"lisi"));
		h.add(new Human(20,"wangwu"));
		h.add(new Human(17,"zhangsan"));
		Iterator it = h.iterator();
		
		while(it.hasNext()){
			Human human = (Human)it.next();
			print(human.getAge() + human.getName());
		}
	}
	public static void print(Object obj){
		System.out.println(obj);
	}
}

class Human{
	private int age;
	private String name;
	Human(int age,String name){
		this.age = age;
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public String getName() {
		return name;
	}
	public int hashCode(){
		System.out.println("calling the hashCode");
		return this.age++;
	}
	public boolean equals(Object obj){
		if(!(obj instanceof Human)){
			return false;
		}
		Human human = (Human) obj;
		return this.age == human.age && this.name.equals(human.name) ;
	}
}

tips:

1.底層實現爲哈希表。

2.HashSet裏的元素是唯一的,無序的。

3.HashSet內元素唯一性的機制:

先判斷hashCode值是否相同,再調用equals方法。

(必須自己重寫int hashCode方法和boolean equals(Object obj)方法)

4.線程不同步。

TreeSet:可以實現Comparable接口對集合內的元素進行排序。

底層數據結構爲二叉樹。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章