Set容器

特点:

  无序,不重复

HashSet和TreeSet

 

HashSet

HashSet扩展AbstractSet并且实现Set接口,底层使用HashSet

HashSet的内部操作的底层数据是HashMap,只是我们操作的是HashMap的key

区分可以采用重写equals()和hashCode()方法

package com.Set;

import java.util.HashSet;

public class HahSetDemo {
  public static void main(String[] args) {
    HashSet<String> data=new HashSet<String>();
    //不允许重复,实际操作的是hashmap里面的键  键只允许唯一
    data.add("张三");
    data.add("李四");
    data.add("王五");
    System.out.println(data.add("张三"));
    System.out.println(data);
    //没有重复   对象都是new出来的
    HashSet<Student1> data2=new HashSet<Student1>();
    data2.add(new Student1("张三", 20));
    data2.add(new Student1("李四", 30));
    System.out.println(data2.add(new Student1("张三", 20)));
}
}

class Student1{
    private String name;
    private int age;
    public Student1(String name, int age) {
        
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student1 other = (Student1) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    };
    
    
}
posted @ 2018-11-20 20:44  言西早石头侠  阅读(118)  评论(0编辑  收藏  举报