本文已参与「新人创作礼」活动,一起开启掘金创作之路。
package com.hike.javase.object;
/*
* boolean equals(Objecr obj):
* 判断当前对象中的内容是否和参数中的对象内容相同
*
* public int hashCode():计算出对象的哈希码(散列码或特征码):
// 根据对象的内容创建出来的特征码值(根据某种规则),对象内容相同则哈希码必须相同,反之亦同
*
* public String toString():把对象变成字符串,字符串内容是对象的详细信息
* 打印对象、完成字符串拼接时,会自动调用toString()方法
*/
public class Point {
private int x;
private int y;
public Point() {
super();
}
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;
}
public String say() {
return "x:" + x + ",y:" + y;
}
@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;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + ", getX()=" + getX() + ", getY()=" + getY() + ", say()=" + say()
+ ", hashCode()=" + hashCode() + ", getClass()=" + getClass() + ", toString()=" + super.toString()
+ "]";
}
}
package com.hike.javase.object;
/*
* boolean equals(Objecr obj):
* 判断当前对象中的内容是否和参数中的对象内容相同,但它其实是一个虚方法,需要根据需求的不同,更改其内容
*/
public class PointTest {
public static void main(String[] args) {
Point p1 = new Point(11,22);
Point p2 = new Point(13,20);
boolean res = p1.equals(p2);
System.out.println(res);
// 哈希码(散列码或特征码):
// 根据对象的内容创建出来的特征码值(根据某种规则),对象内容相同则哈希码必须相同,反之亦同
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
System.out.println(p1);
}
}