黑马程序员技术交流社区
标题:
hascode 问题
[打印本页]
作者:
杨杨
时间:
2013-3-2 15:01
标题:
hascode 问题
本帖最后由 杨杨 于 2013-3-2 15:03 编辑
package cn.itcast.day1;
public class ReflectPoint {
private int x;
private int y;
public String str1="ab";
public String str2="abc";
public ReflectPoint(int x,int y){
/*System.out.println("x:"+x+"y:"+y);
this.x=x;
this.y=y;*/
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String getStr1() {
return str1;
}
public void setStr1(String str1) {
this.str1 = str1;
}
public String getStr2() {
return str2;
}
public void setStr2(String str2) {
this.str2 = str2;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((str1 == null) ? 0 : str1.hashCode());
result = prime * result + ((str2 == null) ? 0 : str2.hashCode());
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReflectPoint other = (ReflectPoint) obj;
if (str1 == null) {
if (other.str1 != null)
return false;
} else if (!str1.equals(other.str1))
return false;
if (str2 == null) {
if (other.str2 != null)
return false;
} else if (!str2.equals(other.str2))
return false;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public String toString(){
return str1+str2;
}
}
复制代码
package cn.itcast.day1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
public class ReflectTest2 {
/**
* @param args
*/
public static void main(String[] args) {
Collection collection = new HashSet();
ReflectPoint point1= new ReflectPoint(3,3);
ReflectPoint point2= new ReflectPoint(3,4);
ReflectPoint point3= new ReflectPoint(3,3);
collection.add(point1);
collection.add(point2);
collection.add(point3);
collection.add(point1);
// point1.setY(7);
collection.remove(point1);
System.out.println(collection.size());
}
}
复制代码
构造方法RelefetPoint 类的构造函数 中的 this 加上注释后 输出size 变成0 求解释
作者:
lzw123451
时间:
2013-3-2 16:31
你把它注释了,就会出现new ReflectPoint(x,y);创建对象时无论X、y等于多少,都会创建一个x=0、y=0(默认初始化值)的对象。
Collection collection = new HashSet();
ReflectPoint point1= new ReflectPoint(3,3);
ReflectPoint point2= new ReflectPoint(3,4);
ReflectPoint point3= new ReflectPoint(3,3);
collection.add(point1);
collection.add(point2);
collection.add(point3);
collection.add(point1);
这样你的语句,其实就是只加了 一个对象 new ReflectPoint(0,0);
而后你又把它删除了
collection.remove(point1);
所以结果就为0咯
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2