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接口对集合内的元素进行排序。

底层数据结构为二叉树。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值