_043_Set集合、HashSet

=================

Set也是一个接口,Set容器具备的特点是无序和无重复元素,添加进去的元素和出来的元素顺序是不同的

实现了hashSet和TreeSet接口

Set的方法和Collection的方法是一模一样的,它的子类hashSet比它的方法还少,但是TreeSet的方法多

因为Set添加进去的元素和出来的元素顺序是不同的,所以Set的add方法肯定是被重写的

hashSet原理:
     1 首先add方法会先调用 元素的hashCode方法,这个方法是Object的,所以是都可以调用,每new一个Person,那么都会产生不同的

hashCode(内存地址)

     2 所以要判断ID,应该是去修改hashCode方法,但是只修改hashCode方法是没有用的

     3 hashCode算出来的数值是分2种情况储存的,

         1 我们hashCode计算返回的数值(可以通过重写只返回id)在一张表上,如果表上面没有数值

             那么该元素可以存到该位置上  

          2 如果算出的元素的位置在hash表里已经存在元素,那么会

            equals方法再比较一次, 如果返回true,那么不可以再存,如果返回false则可以存,

             hash表是桶状的,所以存2个数值,要让其不添加重复,就必须还要重写equals方法,让其只判断ID  

需求1 set虽然说不能添加重复元素,但是如果我们添加的是对象呢,我们的要的是对象的属性id不重复

重复的就不能添加进去

class Test
{
	public static void main(String[] args)
	{
		Set<Person> set1 = new HashSet<Person>();
		set1.add(new Person("aa", 100));
		set1.add(new Person("bb", 101));
		set1.add(new Person("cc", 102));
		set1.add(new Person("dd", 102));
		
		System.out.println(set1);
	}
}

class Person
{
	String name;
	int id;

	public Person(String name, int id)
	{
		this.id = id;
		this.name = name;
	}

	public String toString()
	{
		return name;
	}

	public int hashCode()
	{
		return id;
	}

	public boolean equals(Object o)
	{
		Person person1 = (Person) o;
		return person1.id == id;
	}
}

 这里我们的hashCode被调用了4次,而equals被调用了一次,因为equals只有在hash表里位置已经存在数值时才被调用

猜你喜欢

转载自blog.csdn.net/yzj17025693/article/details/82759200