String toString()和equals()
/**
- 测试object相关的方法
- @author Administrator
/
public class Demo {
private int x;
private int y;
public Demo(int x, int y) {
super();
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Demo d=new Demo(1,2);
/*
* object两个常被重写的方法
* 1:String toString()
* 该方法的设计意义是将一个对象转换为一个字符串
* Object本身实现的toString方法返回的是该对象的"句柄",即该对象的
* 引用信息(地址)
* 格式为:类名@地址
/
System.out.println(d.toString());//object.Point@7852e922
/*
* System.out.println(Object obj)
* 该方法就是将给定对象的toString方法返回的字符串输出到控制台
/
System.out.println(d);
/*
* 2:
* boolean equals(Object obj)
* 该方法用于比较当前对象(this)与参数对象obj的内容比较,
* 当两个对象相同时equals方法返回值应当是true
/
Point p=new Point(1,2);
Point p1=new Point(1,2);
System.out.println(pp1);
/*
* equals方法在不重写的情况下,object定义的是使用""比较的,name就没有意义
*/
System.out.println(p.equals(p1));
}
}
/**
- 使用当前类测试object相关方法的重写
- @author lemon
*/
public class Point{
private int x;
private int y;
public Point(int x, int y) {
super();
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;
}
/**
* 通常我们使用一个类的toString方法,就应当重写这个方法(java API提供的类大部分都已经重写了,无需我们重写)
* 返回的字符串没有严格的格式要求,但应当包含这个字符的属性信息,便于通过返回的字符串了解当前对象的属性信息.
*/
public String toString() {
//[1,2]
return "["+x+","+y+"]";
}
/**
* 当我们需要使用某个类的equals方法判断内容相同时,应当重写这个方法.
* 注:java API提供的类基本都重写了
*/
@Override
public int hashCode() {//散列码,
final int prime = 31;
int result = 1;
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;
Point other = (Point) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
/*public boolean equals(Object obj) {
if(obj==null) {
return false;
}
if(obj==this) {
return true;
}
if(obj instanceof Point) {
Point p=(Point) obj;
if(this.x==p.x&&this.y==p.y) {
return true;
}
}
return false;
}*/
}