File tree Expand file tree Collapse file tree 1 file changed +38
-3
lines changed
Expand file tree Collapse file tree 1 file changed +38
-3
lines changed Original file line number Diff line number Diff line change @@ -131,10 +131,45 @@ public interface RandomAccess {
131131** ` hashCode() ` 与 ` equals() ` 的相关规定:**
132132
1331331 . 如果两个对象相等,则 ` hashcode ` 一定也是相同的
134- 2 . 两个对象相等, 对两个 ` equals() ` 方法返回 true
134+ 2 . 两个对象相等, 对两个 ` equals() ` 方法返回 true
1351353 . 两个对象有相同的 ` 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
You can’t perform that action at this time.
0 commit comments