java集合 HashSet

来源:互联网 发布:代理商查询系统源码 编辑:程序博客网 时间:2024/06/17 04:53

HashSet中如果要放入一个自己定义的类实例的时候比如Person类实例,这时候我们要自己重hashcode和equal方法,用自己的关键字段来重写,因为当使用HashSet时,hashCode()方法就会得到调用,判断已经存储在集合中的对象的hash code值是否与增加的对象的hash code值一致;如果不一致,直接加进去;如果一致,再进行equals方法的比较,equals方法如果返回true,表示对象已经加进去了,就不会再增加新的对象,否则加进去。

先调用hashCode()方法,-->判断存放的链表位置

再调用equals()方法,-->判断对应链表上有没有相同的元素,有的话就不能再放,

import java.util.HashSet;import java.util.Set;public class SetTest1 {public static void main(String[] args) {Set<Student1> set=new HashSet<Student1>();set.add(new Student1("B1000","小明","male",20));//[[id=B1000, name=小明, sex=male, age=20]]System.out.println("set="+set);set.add(new Student1("B1000","小明"));//学号相同,认为是同一个学生,Set集合不能放入相同的元素,所有不能再放入System.out.println("set="+set);//[[id=B1000, name=小明, sex=male, age=20]]set.add(new Student1("B1000","小明","male",20));System.out.println("set="+set);set.add(new Student1("B1001","小明","male",20));set.add(new Student1("B1002","小明","male",20));System.out.println("set="+set);//显示hashSet集合Student1.printSet(set);}}/*class Student1{private String id;private String name;private String sex;private int age;public Student1(){}public Student1(String id,String name,String sex,int age){this.id=id;this.name=name;this.sex=sex;this.age=age;}public Student1(String id,String name,String sex){this.id=id;this.name=name;this.sex=sex;}public Student1(String id,String name){this.name=name;this.id=id;}@Overridepublic String toString() {return "[id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";}//如果学号相同,那就认为学生相同@Overridepublic boolean equals(Object obj){Student1 student1=(Student1)obj;return this.id.equals(student1.id);}@Overridepublic int hashCode() {// TODO Auto-generated method stub//return super.hashCode();//调用String类型的hashCode()方法return this.id.hashCode();}//遍历方法public static void  printSet(Set set){System.out.println("{");for(Iterator<Student1> iterator=set.iterator();iterator.hasNext();){Student1 student1=iterator.next();System.out.print(student1+"\n");}System.out.print("}");}}*/

原创粉丝点击