HashSet add() 方法存储自定义类型对象执行过程分析

  • 创建一个Student类,重载构造方法
public class Student {
	private String id;
	
	public Student() {
	}

	public Student(String id) {
		this.id = id;
	}
	
	public String getId() {
		return id;
	}
}
  • 创建HashSet 把Student对象存入
		HashSet<Student> hashSet = new HashSet<>();
		boolean flag;
		//添加第一个Student对象,id为1
		flag = hashSet.add(new Student("1"));
		System.out.println(flag);
=		//添加第二个Student对象,id为2
		flag = hashSet.add(new Student("2"));
		System.out.println(flag);
		//添加第三个Student对象,id为2
		flag = hashSet.add(new Student("2"));
		System.out.println(flag);

结果:

true
true
true

从结果看到三个对象都添加成功了。
下面分析一下添加的过程

  1. HashSet hashSet = new HashSet<>();
//	  HashSet的无参构造方法
	  public HashSet() {
	        map = new HashMap<>();
	    }
  1. flag = hashSet.add(new Student(“1”));
// 	HashSet的add方法
	public boolean add(E e) {
	//	在1中床创建的map对象执行了put方法
        return map.put(e, PRESENT)==null;
    }
  1. map.put(e, PRESENT)==null
//  HashMap的put方法
	public V put(K key, V value) {
		//这里先执行了hash方法然后执行putVal方法
        return putVal(hash(key), key, value, false, true);
    }
  1. HashMap类中的hash方法
//	HashMap的hash方法
    static final int hash(Object key) {
        int h;
//      如果在2中添加的对象不为空的时候将会调用传入对象的hashCode方法,否则返回0
//		因为这里Student类并没有重写Object类中的hashCode方法
//		所以这里其实这里执行的是从Object继承的hashCode方法
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
//HashMap中的putVal方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //1.把table的值赋给tab,如果是第一次添加则执行if里面的代码,
        //table,seize(),tab指向同一数组,n就是数组的长度
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //2.这里在n相同,
        //由于每次添加Student对象的时候由于调用的是从Object继承的hashCode方法
        //所以每次添加对象的时候得到不同的i。
       	//每个tab[i]在之前并没有赋值,默认为null
       	//所以执行if下面的代码,就把对象添加进去了。直接跳出if语句执行后面的的代码
       	//2*.如果两个对象的hash方法返回值值相同的时候,找到之前存入元素的索引,
       	//则tab[i]中不为null,就会执行执行else语句中的内容
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //3*.从上面可以知道,当前元素,和之前的元素的hash方法返回值相等
            if (p.hash == hash &&
            	//之前存入对象的地址引用和当前对象的地址引用并不相同,也都不为null
            	//而这里调用了当前传入对象的equeals方法,
            	//如果返回true则执行if下面的代码,把之前对象的引用赋给e,
            	//跳出if语句执行后面的代码
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)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;
                }
            }
            //4*.因为e指向之前对象所以e不为null,返回oldValue
            //而HashMap中的put方法返回该方法(putVal)的返回值,
			//所以在HashSet中的add方法map.put(e, PRESENT)也为oldValue
			//因为oldValue==null结果为false,所以add方法返回false,添加失败
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
//      3.执行下面的代码返回null,
//		而HashMap中的put方法返回该方法(putVal)的返回值,
//		所以在HashSet中的add方法map.put(e, PRESENT)也为null
//		因为null==null结果为true,那么add方法将会返回true,添加成功
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

分析源代码之后我们进行简单的应用:
这里我们认为由Student类创建的对象,如果他们的属性(id)相同,则认为这两个对象相同。也就是说,如果Student对象的id相同那么他们就不能同时添加到HashSet集合中,只有第一个对象可以添加成功,其他的将会添加失败。

在Student重写hashCode方法和equals方法

public class Student {
	private String id;

	public Student() {
	}

	public Student(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	@Override
	public int hashCode() {
		//这里id调用了String类中的hashCode方法
		//如果两个字符串相同,那么他们的hashCode返回值也相同
		return id.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		//向下转型
		Student student = (Student)obj;
		//调用id的equals方法,因为id为String类型这里调用的是String类中的equals方法
		//如果两个字符串的内容完全相同,那么equals方法返回true
		return id.equals(student.id);
	}
}

执行测试程序

		public static void main(String[] args) {
		HashSet<Student> hashSet = new HashSet<>();
		boolean flag;
		flag = hashSet.add(new Student("1"));
		System.out.println(flag);
		flag = hashSet.add(new Student("2"));
		System.out.println(flag);
		flag = hashSet.add(new Student("2"));
		System.out.println(flag);
		flag = hashSet.add(new Student("1"));
		System.out.println(flag);
	}

结果

true
true
false
false

注意:当泛型为Object的时候传入其他的非Student类的时候有可能会出现异常
如下,创建一个Dog对象,

public class Dog {
	private String id;
	
	public Dog() {
	}

	public Dog(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}
	
	@Override
	public int hashCode() {
		return id.hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		Dog dog = (Dog)obj;
		return id.equals(dog.id);
	}

}

执行测试代码

		public static void main(String[] args) {
			HashSet<Object> hashSet = new HashSet<>();
			boolean flag;
			flag = hashSet.add(new Dog("1"));
			System.out.println(flag);
			flag = hashSet.add(new Student("1"));
			System.out.println(flag);
			flag = hashSet.add(new Student("2"));
			System.out.println(flag);
			flag = hashSet.add(new Student("2"));
			System.out.println(flag);
			flag = hashSet.add(new Student("1"));
			System.out.println(flag);
		}

结果

true
Exception in thread "main" java.lang.ClassCastException: test.Dog cannot be cast to test.Student
	at test.Student.equals(Student.java:33)
	at java.util.HashMap.putVal(Unknown Source)
	at java.util.HashMap.put(Unknown Source)
	at java.util.HashSet.add(Unknown Source)
	at test.Test.main(Test.java:11)

这是因为当添加由Dog类创建的对象的时候,因为他的hashCode是字符串"1"调用String类中的hashCode方法,和第一个Student(“1”)对象的hashCode返回值相同,
那么Student对象会调用它的equals方法,并把Dog对象传入

	@Override
	public boolean equals(Object obj) {
		//这里把Dog对象传入,直接把Dog对象类型转换为Student对象
		//而Dog类和Student类并没有子父类关系,这里会报异常
		//在异常的信息提示里可以看出来
		//at test.Student.equals(Student.java:33)
		//也就是下面这一行代码
		Student student = (Student)obj;
		return id.equals(student.id);
	}

所以这里的解决方法可以在equals方法中添加instanceof关键字判断传入对象和Student的关系
比如

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Student) {
			Student student = (Student) obj;
			return id.equals(student.id);
		}
		return false;
	}

同样Dog类中也要添加该语句

@Override
	public boolean equals(Object obj) {
		if (obj instanceof Dog) {
			Dog dog = (Dog) obj;
			return id.equals(dog.id);
		}
		return false;

测试代码

public static void main(String[] args) {
			HashSet<Object> hashSet = new HashSet<>();
			boolean flag;
			flag = hashSet.add(new Dog("1"));
			System.out.println(flag);
			flag = hashSet.add(new Student("1"));
			System.out.println(flag);
			flag = hashSet.add(new Student("2"));
			System.out.println(flag);
			flag = hashSet.add(new Student("2"));
			System.out.println(flag);
			flag = hashSet.add(new Student("1"));
			System.out.println(flag);
		}

结果

true
true
true
false
false

通过以上的分析可以知道,HashSet在调用的add方法添加元素的时候,主要调用了传入对象的hashCode方法和equals方法。
而且由源码分析可以知道,只有在对象的hashCode返回值相同的时候才会调用传入对象的equals方法,否则不会调用。

猜你喜欢

转载自blog.csdn.net/qq_35302939/article/details/89738528
今日推荐