Set集合之hashCode()和equals()

package com.day15.Set;
/*
* set集合中的元素不能重复(唯一性),也没索引,存取无序
*/

import java.util.HashSet;

import com.day15.bean.Person;

public class HashSet_One {

public static void main(String[] args) {
  /*HashSet<String> hs=new HashSet<>();
  hs.add("a");
  hs.add("a");
  hs.add("b");
  hs.add("c");
  hs.add("d");
  System.out.println(hs);//[a, b, c, d]
    for(String str:hs) {
    System.out.print(str);//abcd
  }*/
  HashSet<Person> hs1=new HashSet<>();
    hs1.add(new Person("Kobe",20));//Person类中必须要重写hashCode()和equals()方法
    hs1.add(new Person("Kobe",20));
    hs1.add(new Person("KG",21));
    hs1.add(new Person("KG",21));
    hs1.add(new Person("KG",21));
    hs1.add(new Person("PP",22));
    for(Person p:hs1) {
      System.out.print(p);//Kobe,20KG,21PP,22
    }
  }
}

posted @ 2018-05-12 17:22  简简单单zjl  阅读(226)  评论(0编辑  收藏  举报