Skip to content

Commit a22f412

Browse files
committed
Update b-2Java集合.md
1 parent af370ce commit a22f412

File tree

1 file changed

+38
-3
lines changed

1 file changed

+38
-3
lines changed

docs/b-2Java集合.md

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,45 @@ public interface RandomAccess {
131131
**`hashCode()``equals()` 的相关规定:**
132132

133133
1. 如果两个对象相等,则 `hashcode` 一定也是相同的
134-
2. 两个对象相等,对两个 `equals()` 方法返回 true
134+
2. 两个对象相等对两个 `equals()` 方法返回 true
135135
3. 两个对象有相同的 `hashcode` 值,它们也不一定是相等的
136-
4. 综上,`equals()` 方法被覆盖过,则 `hashCode()` 方法也必须被覆盖
137-
5. `hashCode() `的默认行为是对堆上的对象产生独特值。如果没有重写 `hashCode()`,则该 class 的两个对象无论如何都不会相等(即使这两个对象指向相同的数据)。
136+
137+
综上,如果一个类的 `equals()` 方法被覆盖过,则 `hashCode()` 方法也必须被覆盖。
138+
139+
` hashCode()` 的默认⾏为是对堆上的对象产⽣独特值。如果没有重写 `hashCode() `,即使通过 `equals()` 判断为相同的两个对象,在加入 `HashSet` 时,也不会被 `HashSet` 认为是重复对象。
140+
141+
```java
142+
import java.util.HashSet;
143+
144+
public class People {
145+
String idCard;
146+
147+
public People(String idCard) {
148+
this.idCard = idCard;
149+
}
150+
151+
@Override
152+
public boolean equals(Object o) {
153+
if (this == o) return true;
154+
if (o == null || getClass() != o.getClass()) return false;
155+
People people = (People) o;
156+
return idCard.equals(people.idCard);
157+
}
158+
159+
public static void main(String[] args) {
160+
People a = new People("a");
161+
People a1 = new People("a");
162+
// output: true
163+
System.out.println(a.equals(a1));
164+
165+
HashSet<People> set = new HashSet<>();
166+
set.add(a);
167+
set.add(a1);
168+
// output: 2
169+
System.out.println(set.size());
170+
}
171+
}
172+
```
138173

139174
**==与 equals 的区别**
140175

0 commit comments

Comments
 (0)