浅析HashSet add() 方法存储自定义类型对象的过程

  一、自定义一个Student类

  package date0504;

  public class Student {

  private String id;

  Student(String id){

  this.id=id;

  }

  public String getId() {

  return id;

  }

  public void setId(String id) {

扫描二维码关注公众号,回复: 6124427 查看本文章

  this.id = id;

  }

  }

  二、使用HashSet中的add()方法将上述对象存入

  HashSet hashset = new HashSet<>();

  //add()方法的返回值为boolean类型。若为true,存入成功。否则,数据存入失败。

  System.out.println(hashset.add(new Student("1"))); //存入第一个对象

  System.out.println(hashset.add(new Student("2"))); //存入第二个对象

  System.out.println(hashset.add(new Student("1"))); //存入第三个对象

  输出结果如下

  true

  true

  true

  三、从上述结果看出,三个对象都添加成功了。我们来分析一下add()方法的具体过程。

  1、HashSet hashset = new HashSet<>(); 第一行代码调用了HashSet的无参构造方法,我们来看一下它的源码。

  public HashSet() {

  map = new HashMap<>(); //调用了HashMap无参构造方法,创建了map对象。

  }

  2、我们主要分析第三行代码——hashset.add(new Student("1");

  //HashMap中的add方法

  public boolean add(E e) {

  return map.put(e, PRESENT)==null; //调用了HashMap中的put方法

  }

  3、再来看这行代码———map.put(e, PRESENT)==null;

  //HashMap中的put方法

  public V put(K key, V value) {

  return putVal(hash(key), key, value, false, true); //调用本类中的putVal方法和hash方法。

  }

  4、让我们来看一下HashMap中的hash方法

  static final int hash(Object key) {

  int h;

  // 若传入对象不为null,则返回此对象调用hashCode方法(其实是Object类中的hashCode方法)的返回值

  return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

  }

  5、分析HashMap中的putVal方法。

  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,

  boolean evict) {

  Node[] tab; Node p; int n, i;

  //1、第一次添加对象时,tab为null,执行其后语句。

  if ((tab = table) == null || (n = tab.length) == 0)

  n = (tab = resize()).length; //2、如果存储元素的table为空,则进行必要字段的初始化,n为初始化后数组长度。

  //3、第一次传入数据时,p=null,执行if语句下面的代码。第二次添加数据时的n和第一次添加后的n一样,但是不同传入对象的hash值是不一样的,所以i不同,p=null。故每次传入不同对象p都为null,不会执行else语句块。

  if ((p = tab[i = (n - 1) & hash]) == null)

  tab[i] = newNode(hash, key, value, null);

  //4、如果两个对象的hash值一样,p就不为null,就执行else语句块。

  else {

  Node e; K k;

  //5、当前元素和上一个元素的hash值相等

  if (p.hash == hash &&

  //6、当前对象的地址和之前对象的地址不同,也不为null。并且这里调用了当前传入对象的equals方法。

  ((k = p.key) == key || (key != null && key.equals(k))))

  //7、如果if语句为true,把之前的对象赋值给e。

  e = p;

  else if (p instanceof TreeNode)

  e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);

  else {

  for (int binCount = 0; ; ++binCount) {

  if ((e = p.next) == null) {

  p.next = newNode(hash, key, value, null);

  if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st

  treeifyBin(tab, hash);

  break;

  }

  if (e.hash == hash &&

  ((k = e.key) == key || (key != null && key.equals(k))))

  break;

  p = e;

  }

  }

  //8、e不为null,故返回 oldValue。

  //9、HashMap中的put方法也返回oldValue。

  //10、oldValue不为null,故add方法返回false。

  if (e != null) { // existing mapping for key

  V oldValue = e.value;

  if (!onlyIfAbsent || oldValue == null)

  e.value = value;

  afterNodeAccess(e);

  return oldValue;

  }

  }郑州 不  孕 不  育 医  院:http://jbk.39.net/yiyuanzaixian/zztjyy/

  //11、若执行下面代码,则返回null,add方法返回值为true。添加不同的对象都会执行下面代码。

  ++modCount;

  if (++size > threshold)

  resize();

  afterNodeInsertion(evict);

  return null;

  }

  四、那我们分析完add方法的执行过程后,该如何实现不能重复添加id相同的Student对象这个目的呢?

  1、在Student类中重写hashCode方法和equals方法

  public class Student {

  private String id;

  Student(String id){

  this.id=id;

  }

  public String getId() {

  return id;

  }

  public void setId(String id) {

  this.id = id;

  }

  public boolean equals(Object o) {

  Student stu =(Student)o; //向下转型

  return id.equals(stu.id); //id为String类型,故只要两个字符串内容相同,返回true。

  }

  public int hashCode() {

  return id.hashCode(); //调用了String类中的hashCode方法,如果两个字符串相同,那hashCode方法返回true。

  }

  }

  2、使用HashSet存入对象。

  HashSet hashset = new HashSet<>();

  //add()方法的返回值为boolean类型。若为true,存入成功。否则,数据存入失败。

  System.out.println(hashset.add(new Student("1"))); //存入第一个对象

  System.out.println(hashset.add(new Student("2"))); //存入第二个对象

  System.out.println(hashset.add(new Student("1"))); //存入第三个对象

  输出结果如下

  true

  true

  false

  3、可以看出:当重写了hashCode方法和equals方法后,就实现了此目的。

  五、注意事项

  1、当泛型为Object的时候传入其他的非Student类的时候有可能会出现异常。

  HashSet

猜你喜欢

转载自www.cnblogs.com/dream8023/p/10812551.html