HashSet的使用

来源:互联网 发布:大数据阅读答案 编辑:程序博客网 时间:2024/06/06 02:27
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接口对集合内的元素进行排序。

底层数据结构为二叉树。