如:
public class Test
{
Point p1=new Point(1,1);
Point p2=new Point(1,1);
问题:
如何才能判断p1与p2是否相等
怎么做才能让p1等于p2呢?
}
class Point
{
int x,y;
public Point(int x,int y)
{
this.x=x;
this.y=y;
}
}
解决方案 »
- stringbuffer问题
- jms和socket一起使用的问题,跪求
- 我是java初学者,遇到了几个问题,请各位高手帮帮忙。
- Exception in thread "main" java.lang.Error: Unresolved compilation problems:
- 关于反射机制的问题
- 如何通过浏览选择文件并通过socket传输?
- 进程和线程的区别?
- 学java到了瓶颈了,应该怎么办?
- 已有的一棵tree,如何得到他的root节点?
- java 中出现的小问题.(在线急!!)
- 我创建了两个jframe ,一个是是用来显示数据的,一个是用来添加数据的,如何添加数据时候显示数据页即时显示出添加的数据呢。
- jdk15_15012_ia.depot怎么用啊?
p1=p2
用这样后,他们的引用是相同的
public class Test
{
public static void main (String[] args)
{
Point p1=new Point(1,1);
Point p2=new Point(1,1);
//问题:
//如何才能判断p1与p2是否相等
//怎么做才能让p1等于p2呢? System.out.println(p1.equals(p2));
//实际上p1无法等于p2,再像的双胞胎也还是不同的两个人
//对象相等了就是同一个对象的引用了
}
}
class Point
{
int x,y;
public Point(int x,int y)
{
this.x=x;
this.y=y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public boolean equals(Object o)
{
if(((Point)o).getX()==x&&((Point)o).getY()==y)
{
return true;
}
else return false;
}
}
if (obj == this) return true;
if (obj == null) return false;
if (obj.getClass() != this.getClass()) return false;
Point other = (Point) obj;
return other.x == this.x && other.y == this.y;
}使用p1.equals(p2);