有关 java 重写equals 方法,判断两个点是否相同,public class Point{\x05 private double x;\x05 \x05 private double y;\x05 \x05 public Point(){\x05 \x05 \x05 \x05 this(5,0);\x05 \x05 \x05 }\x05 \x05 public Point(double x){\x05 \x05\x05 this
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/23 08:10:10
有关 java 重写equals 方法,判断两个点是否相同,public class Point{\x05 private double x;\x05 \x05 private double y;\x05 \x05 public Point(){\x05 \x05 \x05 \x05 this(5,0);\x05 \x05 \x05 }\x05 \x05 public Point(double x){\x05 \x05\x05 this
有关 java 重写equals 方法,判断两个点是否相同,
public class Point{
\x05 private double x;
\x05
\x05 private double y;
\x05
\x05 public Point(){
\x05 \x05
\x05 \x05 this(5,0);
\x05 \x05
\x05 }
\x05
\x05 public Point(double x){
\x05 \x05
\x05 this(x,0);\x05
\x05 }
\x05
\x05 public Point(double x,double y){
\x05 \x05 super();
\x05 \x05 this.x = x;
\x05 \x05 this.y = y;
\x05 \x05
\x05 }
\x05
\x05 public void setX(double x){
\x05 \x05
\x05 \x05 this.x = x;
\x05 }
\x05
\x05 public double getX(){
\x05 \x05
\x05 \x05 return this.x;
\x05 }
\x05
\x05 public void setY(double n){
\x05 \x05
\x05 \x05 this.y = y;
\x05 }
\x05
\x05 public String toString(){
\x05 \x05
\x05 \x05 return this.x + "," + this.y;
\x05 }
\x05
//我就是不理解if 里面,为什么要这么写
\x05 public boolean equals(Point p){
\x05 \x05 if(this.x == p.getX() && this.y == p.getY() ){
\x05 \x05 \x05
\x05 \x05 \x05 return true;
\x05 \x05 }else{
\x05 \x05 \x05 return false;
\x05 \x05 }
\x05 \x05
\x05 }
\x05
\x05 public double getY(){
\x05 \x05
\x05 \x05\x05\x05return this.y;
\x05 }
\x05
\x05 public static void main(String[] args){
\x05 \x05
\x05 \x05
\x05 \x05
}
}
public class TestWraper{
\x05
\x05 public static void main(String[] args){
\x05 \x05
\x05 \x05 Integer i = new Integer(10);
\x05 \x05 Integer j = new Integer(10);
\x05 \x05 System.out.println(i.equals(j));
\x05 \x05 System.out.println(i.intValue() + 1);
\x05 \x05
\x05 \x05 String s = new String("devil");
\x05 \x05
\x05 \x05 Point p = new Point();
\x05 \x05 System.out.println(p);
\x05 \x05
\x05 \x05 Point p1 = new Point(3 ,3);
\x05 \x05 Point p2 = new Point(3 ,3);
\x05 \x05
\x05 \x05 System.out.println(p1.equals(p2));
\x05\x05\x05 }
\x05
\x05
}
我的想法是 判断两个点的X,Y分别是否相等,但是这个程序if 里面写的我看不太明白,this.x 指的是对象本身的吧?和p.getX()相比是什么意思啊,这不是自己跟自己对比吗?我的理解应该是错误的.
有关 java 重写equals 方法,判断两个点是否相同,public class Point{\x05 private double x;\x05 \x05 private double y;\x05 \x05 public Point(){\x05 \x05 \x05 \x05 this(5,0);\x05 \x05 \x05 }\x05 \x05 public Point(double x){\x05 \x05\x05 this
当然不一样,给你举个例子
Point p1 = new Point(11,11);
Point p2 = new Point(22,22);
p1.equals(p2); //这就是equals的用法
你看,分明是两个对象,怎么会一样呢.
----------------------------------------------------------
楼主 我问你 怎么判断这两个点相等呢?
那就是x点坐标与y点坐标都一样不就是相等的么!