HashSet类中的add方法

这里我们首先创建一个HashSet

参数为String

public class Test {
public static void main(String[] args) {
HashSet<String> set =new HashSet<String>();
System.out.println(set.add("张三"));
System.out.println(set.add("张三"));
  }
}

这时候输出一定是true  false

 

add方法源代码

public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

 调用HashSet的add方法实质上是调用HashMap的put方法,map是全局,变量它指向的是在创建HashSet对象时创建的HashMap对象。如果put方法返回值为null则add方法返回true,证明添加成功;如果put方法返回值非null则add方法返回false,证明添加失败。

 

put方法源码

public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

调用HashSet的add方法实质上是调用HashMap的put方法,这时,put方法的参数key实质上是add 方法中的e,也就是添加对象的地址,put方法中的参数value实质上是一个常量。put方法调用putVal方法,并返回调用结果

 

 

hash方法源码

static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

hashCode方法返回调用对象的地址。所以如果传入对象为空则返回0,否则返回根据所传对象的地址计算的int类型的数值。

 

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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((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;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

 

 在HashSet方法中调用put方法时,putVal方法的第一个参数hash是根据你想要添加的对象的地址而计算的一个int类型的数值;第二个参数key指向你想要添加的对象;第三个参数value是一个常量;第四个参数onlyIfAbsent是布尔型false;第五个参数evict是布尔型true; Node<K,V>[] tab;定义一个数组,数组名是tab,数组元素类型是Node<K,V>。变量p也是一个结点类型。table是一个全局变量,它也是一个存有结点类型的数组。

1、第一次添加“张三”

 首先调用HashSet类中的add方法,实质上是通过HashMap类型的全局变量map调用put方法。紧接着put方法调用putVal方法,执行putVal方法,table是一个全局变量,创建对象时并没有给table赋值,因此,tab = table = null,执行第一个if语句,调用resize方法。这里tab等于resize方法的返回值。

 

resize方法源代码

final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}

在resize方法中,给全局变量table赋值为newTab,newTab初始数组长度为16,并且返回值也为newTab。又因为tab等于resize方法的返回值,所以第一个if语句执行结束后table和tab指向同一个地址,n = 16。

执行第二个if语句,第二个if语句的判断条件是将hash值与(n-1)做按位与运算,动态的找到数组的一个元素,判断是否为null。因为并未给数组tab赋值数组里的元素一定都为null,所以if语句的判断条件一定成立。if语句 tab[i] = newNode(hash, key, value, null);将传入的结点赋值给在if语句判断条件里找到的那个数组元素。

执行第三个也是最后一个if语句,返回null。因为putVal返回值为null,null = null,所以put方法的返回值为true,即add方法的返回值为true,添加成功。

2、第二次添加“张三”

前面执行过程与第一次添加“Student1”时一样,当执行到putVal方法的第二个if语句时,因为table是一个全局变量,添加完第一个“Tom”后,table已经有值了,所以tab = table不等于null,又因为此时n= tab.length = 16,所以第一个if语句的判断条件不成立,执行第二个if语句。第二个if语句的判断条件是“p = tab[i = (n - 1) & hash])”是否为null。在前面我们已经证明过相同字符串的hashCode值一定相等。又因为在对象非空的条件下,hash值与hashCode值直接相关,所以相同对象的hash值一定相同。所以这时,计算的结点p一定是指向第一个“Tom”的结点,结点非空,执行else语句。

else语句中的第一个if的判断条件是“p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))”,首先““p.hash == hash”的结果为true,因为相同对象的hash值一定相同。然后“(k = p.key) == key”的结果也为true,因为(k = p.key) = key = “Tom”。if语句的判断条件成立,执行if语句,e = p;。接着执行else语句中的第二个if语句。

else语句中的第二个if的判断条件是“e != null”,很明显判断条件成立,执行if语句。在if语句中旧的value值被新的value值覆盖,并返回旧的value值。

因为putVal方法的返回值非空,所以put方法的返回值为false,即add方法的返回值为false,添加失败。

 

 

add方法的参数类型是其它类型

1、未重写hashCodeequals方法之前

创建一个学生类

private String id;
public Student(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}

创建一个实现类

public class Test {
public static void main(String[] args) {
HashSet<Student> set =new HashSet<Student>();
Student student1 = new Student("110");
System.out.println(student1.hashCode());
Student student2 = new Student("110");
System.out.println(student2.hashCode());
System.out.println(student1==student2);
System.out.println(set.add(student1));
System.out.println(set.add(student2));
}
}

输出结果:

681842940
1392838282
false
true
true

 

因为student1和student2是两个完全不同的对象,所以它们两个的hashCode值一定不同,hash值一定也不同。所以在putVal方法中根据hash值动态找要添加的结点时,所找的结点一定也不是同一个,所以这两个对象都会添加成功

 

2、重写hashCode方法,未重写equals方法

添加重写hashCode的学生类

public class Student {

private String id;

public Student(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public int hashCode() {
return this.id.hashCode();
}
}

实现类

public class Test {
public static void main(String[] args) {
HashSet<Student> set =new HashSet<Student>();
Student student1 = new Student("110");
System.out.println(student1.hashCode());
Student student2 = new Student("110");
System.out.println(student2.hashCode());
System.out.println(student1==student2);
System.out.println(set.add(student1));
System.out.println(set.add(student2));
}
}

输出结果

48656
48656
false
true
true

重写Student类中的hashCode方法,当调用Student类中的hashCode方法时,实质上调用的是String类中的hashCode方法,返回的是调用对象Id属性的hashCode值。因为student1student2 Id属性上的值都是字符串“110”,所以这两个对象的HashCode值相等。

添加student1对象时,因为此时集合为空,所以一定能添加成功。添加student2对象时,当执行到putVal方法的第二个if语句时(判断条件:(p = tab[i = (n - 1) & hash]) == null),因为student1student2的HashCode值相等,所以student1student2hash值相等。所以studnet1student2动态计算得到的是同一个结点。所以添加studnet2对象时,第二个if语句的判断结果为false。执行else语句。

在else语句中,首先定义两个变量,分别是结点类型和K类型即Studnet类型。执行第一个if语句,判断条件是:p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k)))。因为student1student2对应的hash值相等,所以p.hash == hash的结果是true。因为(((k = p.key) == key)比较的是两个对象的地址,所以运行结果是false。所以key不等于nullkey.equals(k),因为keyK类型即Student类型,所以调用的是Student类中的equals方法,又因为Student类中的equals方法没有被重写,所以实质上调用的是object类中的equals方法。object类中的equals方法比较的是两个对象的地址,所以key.equals(k)的运行结果是false。所以该if语句的判断条件不成立,执行else if语句。

else if语句的判断条件是p instanceof TreeNodeNode类型因为不是TreeNode类型也不是其子类,所以该else if语句的判断条件不成立,执行else语句。

else语句中有一个for循环,for循环中有一个if语句,因为此时集合中只有一个结点p存有值,所以p.next=null,所以e=p.next=null。然后执行if语句体,把新的对象student2存在p.next结点中。break跳出for循环。else语句执行完毕。执行下一个if语句。

因为此时e为null(p.next指向新创建的Node对象,因为e只是引用p.next,所以e还是指向null),所以if语句的判断条件不成立,执行下一个if语句,返回null。

因为putVal方法的返回值为空,所以put方法的返回值为true,所以add方法的返回值为true,添加成功。


3、既重写hashCode方法也重写equals方法

添加重写hashCode和equals的学生类

public class Student {
private String id;
public Student(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public int hashCode() {
return this.id.hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Student) {
Student s = (Student)obj;
return this.id==(s.id);
}
return false;
}
}

实现类

public class Test {
public static void main(String[] args) {
HashSet<Student> set =new HashSet<Student>();
Student student1 = new Student("110");
System.out.println(student1.hashCode());
Student student2 = new Student("110");
System.out.println(student2.hashCode());
System.out.println(student1==student2);
System.out.println(set.add(student1));
System.out.println(set.add(student2));
System.out.println(set.size());
}
}

输出结果

48656
48656
false
true
false
1

 

重写Student类中的equals方法后,当调用Student类中的equals方法时,将执行本类中的equals方法。实质上就是调用String类中的equals方法比较两个Student对象的Id属性是否相等。在重写的equals方法中用if语句判断所传对象是否为Student类,防止不同类但具有相同属性值的对象对重写equals方法的结果造成干扰。

前面的执行过程都一样,当执行到else语句中第一个if语句时,因为重写了Student类中的equals方法,所以if语句的判断条件为true,执行if语句体,e = p。紧接着执行第三个if语句。

第三个if语句的判断条件是,e是否为空。显然if语句的判断条件成立,在该语句体中的返回值为oldvalue,返回值为非空。

因为putVal的返回值非空,所以put方法的返回值为false,即add方法的返回值为false,添加失败。

posted on 2021-05-13 17:34  Fire·  阅读(455)  评论(0编辑  收藏  举报

导航