哈希表的存储自定义对象

哈希表的存储自定义对象

 /*
      *  HashSet集合的自身特点:
      *    底层数据结构,哈希表
      *    存储,取出都比较快
      *    线程不安全,运行速度快
      */
     public class HashSetDemo1 {
      public static void main(String[] args) {
        
        //将Person对象中的姓名,年龄,相同数据,看作同一个对象
        //判断对象是否重复,依赖对象自己的方法 hashCode,equals
        HashSet<Person> setPerson = new HashSet<Person>();
        setPerson.add(new Person("a",11));
        setPerson.add(new Person("b",10));
        setPerson.add(new Person("b",10));
        setPerson.add(new Person("c",25));
        setPerson.add(new Person("d",19));
        setPerson.add(new Person("e",17));//每个对象的地址值都不同,调用Obejct类的hashCode方法返回不同哈希值,直接存入
        System.out.println(setPerson);
      }
     }
    
    public class Person {
      private String name;
      private int 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;
      }
      public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
      }
      public Person(){}
      
      public String toString(){
        return name+".."+age;
      }
      }

猜你喜欢

转载自blog.csdn.net/fang0321/article/details/83857483