Java容器(HashSet)

Java容器(HashSet)

HashSet特点

  • set元素无序且不可重复(元素存入的顺序和取出的顺序是不一致的)
  • HashSet是set接口的一个实现类
  • HashSet可以方便高效地实现去重、集合运算等功能,需要使用集合保存一组对象时,如果要求对象不重复,并且对存取的速度快的场景,就可以使用HashSet。

注意:自定义的类要存到Hashset中,就必须重写equals()和hashCode()方法(两个方法必须都重写),因为存入元素时候,HashSet会先使用hashCode方法判断是否相等,然后再使用equals()方法判断是否相等,两者之一判断相等都不可以添入。

HashSet例子

创建一个Person类

package com.cwstd.day3;

import java.util.Objects;

public class Person {
    private String name;
    private Integer age;
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        Person person=null;
        if(o instanceof Person)
        {
            person=(Person) o;
            if(this.name.equals(person.getName()) && this.age== person.getAge())
            {
                return  true;
            }
        }

        return false;
    }

    @Override
    public int hashCode() {
        int res=this.name==null || this.age==null? 0:this.name.hashCode()+this.age.hashCode();
        return res*17;
    }
}

注意:hashCode一般写法:
例:判断相等的条件name,age,其他条件为sex,hobby

@Override
	public int hashCode() {
		int res=this.name.hashCode()+this.age.hashCode();
		res = 17 * res + sex.hashCode();
		res = 17 * res + hobby.hashCode();
		return res;
	}

测试类

package com.cwstd.day3;

import org.junit.Test;

import java.util.HashSet;
import java.util.Iterator;

public class HashSetTest {
    @Test
    public void addHashSet()
    {
        HashSet<Person> hashSet=new HashSet<>();
        hashSet.add(new Person("cwi",22));
        hashSet.add(new Person("cw",22));
        Iterator<Person> iterator =  hashSet.iterator();
        while(iterator.hasNext())
        {
            Person a=iterator.next();
            System.out.println(a.getName());
            System.out.println(a.getAge());
        }
    }
}
原文地址:https://www.cnblogs.com/cwstd/p/14709817.html