向Set接口中的HashSet集合存入元素

时间:2021-01-22 17:56:48

步骤:
1、创建一个Student类,设置类中的属性,包括私有的id和name。

2、 ps:调用HashSet集合的add方法时,会调用存入对象的hashCode()方法获得对象的哈希值,根据此哈希值计算出一个存储位置,如果该位置没有元素,直接将元素存入,若有元素存在,会调用equals()方法让当前元素和该位置上的元素进行比较,若返回结果为false,就将该元素存入集合,返回结果为true,说明有重复元素,就将该元素舍弃。

重点:所以HashSet需要重写hashCode()方法和equals()方法!!!!!!!!!!!!!!!!

3、重写toString()方法。

4、进行equals()方法时,
(1)判断是否为同一个对象,若为同一个对象,则返回true。
(2)判断是否为Student对象,若不是,则强制转换为Student对象。

(3)判断id值是否相同,若相同,则返回。


5、创建HashSet对象和 Student对象,在主类中进行添加。
6、向集合中添加对象。

package practice1;
import java.util.*;
class Student
{
	private String id;
	private String name;
	public Student(String id,String name)
	{
		this.id=id;
		this.name=name;
	}
	//重写toString方法
	public String toString()
	{
		return id+":"+name;
	}
	//重写hashCode方法
	public int hashCode()
	{
		return id.hashCode();
	}
	//重写equals方法
	public boolean equals(Object obj)
	{
		if(this==obj)
		{
			return true;
		}
		if(!(obj instanceof Student))
		{
			return false;
		}
		Student stu=(Student )obj;
		boolean b=this.id.equals(stu.obj);
		return b;
		
		
	}
}
public class Example07 {

	public static void main(String[] args) {
		HashSet hs=new HashSet();
		Student stu1=new Student("1","Jack");
		Student stu2=new Student("2","Sam");
		hs.add(stu1);
		hs.add(stu2);
		System.out.print(hs);
		
		// TODO Auto-generated method stub

	}

}