---------------------- <a target="blank">ASP.Net+Unity开发</a>、<a target="blank">.Net培训</a>、期待与您交流! ----------------------
示例1:
ReflectTest.java
package com.itheima.day1;
import java.util.ArrayList;
import java.util.Collection;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Collection collections = new ArrayList();
ReflectPoint pt1 = new ReflectPoint(3, 3);
ReflectPoint pt2 = new ReflectPoint(5, 5);
ReflectPoint pt3 = new ReflectPoint(3, 3);
collections.add(pt1);
collections.add(pt2);
collections.add(pt3);
collections.add(pt1);
System. out.println(collections.size());
//结果:4
}
}
示例2:
ReflectTest.java
package com.itheima.day1;
import java.util.Collection;
import java.util.HashSet;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Collection collections = new HashSet();
ReflectPoint pt1 = new ReflectPoint(3, 3);
ReflectPoint pt2 = new ReflectPoint(5, 5);
ReflectPoint pt3 = new ReflectPoint(3, 3);
collections.add(pt1);
collections.add(pt2);
collections.add(pt3);
collections.add(pt1);
System. out.println(collections.size());
//结果:3
}
}
分析:
由以上两示例可以看到当集合为ArrayList时,其实质是一个数组,因此放入4个元素后,集合size为4。
当集合为HashSet时,需要通过比较hashcode值以及equals方法是否返回true决定是否放入。如果hashcode值相等并且equals方法返回true,那么就不会放入。因此,集合size为3。
如果想让size为2,也就是pt1与pt3作为同一个元素存入HashSet集合,那就需要覆盖ReflectPoint类的hashCode方法以及equals方法。
---------------------- <a target="blank">ASP.Net+Unity开发</a>、<a target="blank">.Net培训</a>、期待与您交流! ----------------------
|