Java集合(二)HashSet的使用

HashSet与TreeSet详解
本文通过实例演示了HashSet集合的基本使用方法,包括添加元素、遍历集合、元素去重等特性,并介绍了HashSet与TreeSet的区别及其实现原理。

HashSet和TreeSet都实现了Collection下的Set接口,他们实现的原理分别是HashMap和TreeMap,基本的数据结构是哈希表和Red-Black Tree

package com.pason.hashset;
import java.util.HashSet;
import java.util.Iterator;


public class HashSetDemo {
	public static void main(String[] args) {
		HashSet<Student> student = new HashSet<Student>();
		Student stu1 = new Student("Pason",123);
		Student stu2 = new Student("Wade",456);
		Student stu3 = new Student("Lee",789);
		Student stu4 = new Student("Wong",123);
		student.add(stu1);
		student.add(stu2);
		student.add(stu3);
		student.add(stu4);
		System.out.println(student.size());
		//打印的都是Student对象的toString()方法
		System.out.println("======================");
		//forEach方法遍历
		for (Student s: student)
			System.out.println(s);
		System.out.println("======================");
		//直接打印hashSet对象
		System.out.println(student);
		System.out.println("======================");
		//迭代器
		Iterator<Student> stu = student.iterator();
		while(stu.hasNext()){
			System.out.println(stu.next());
		}
		System.out.println("======================");
		//加入重复元素发现对象加不进去
		student.add(stu3);
		System.out.println(student);
		//如何定义对象是否重复呢?
		//需要重写equals()和hashCode()方法,一般在Eclipse中
		//自动根据类中字段属性重写
		//现在重写Student中的equals()和hashCode()方法
		//仅根据id判断是否一致,这样stu4因为与stu1的id一致,所以只加入了3个
		
		//如果修改某个hashset中元素的能够决定hashcode和equals()的因素,那么修改后该元素无法移除
		//原因和HashMap有关
		stu3.setId(111);
		student.remove(stu3);
		System.out.println("======================");
		System.out.println(student);
		System.out.println("发现无法移除,但该改变可见!");
	}

}

package com.pason.hashset;

public class Student {
	private String name;
	private int id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String toString() {
		return "Student [name=" + name + ", id=" + id + "]";
	}
	public Student(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (id != other.id)
			return false;
		return true;
	}
	

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值