equals方法
public boolean equals(Object obj)指示某个其他对象是否与此对象“相等”。
equals 方法在非空对象引用上实现相等关系:
基本数据类型:比较的是值
引用数据类型:比较的是两个对象的地址值
参数:
obj - 要与之比较的引用对象。
返回:
如果此对象与 obj 参数相同,则返回 true;否则返回 false。
例如:
package tostring;
public class People {
private String name;
private int age;
public People() {
super();
// TODO Auto-generated constructor stub
}
public People(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package tostring;
public class Demo01{
public static void main(String[] args) {
// TODO Auto-generated method stub
People p1=new People("小明",12);
People p2=new People("小明",12);
System.out.println(p1);
System.out.println(p2);
boolean b=p1.equals(p2);
System.out.println(b);
}
}
运行结果为:
tostring.People@5b6f7412
tostring.People@27973e9b
false
如果在Demo01类中把p2的地址值赋值给p1,也就是让p1=p2;
运行结果则变为:
tostring.People@5b6f7412
tostring.People@27973e9b
true
所以equals方法默认比较的对象的地址值,所以没有什么意义,需要重写equals方法,比较两个对象的属性(name,age)。
在People类中添加:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
(快捷键 source -> Generate hasCode()and equals() )
**重写后的运行结果为:
tostring.People@5b6f7412
tostring.People@27973e9b
true
**
Objects类
本类由一些操作对象的静态工具方法构成,这些工具方法包括了非空检查、方法的非空参数检查、
比较对象的hashCode、为对象返回一个字符串表示、比较两个对象
【特点】
该类是使用final修饰,不能被继承
该类的构造方法被私有化(使用private修饰),不能直接创建对象
该类中所有的方法都是静态方法,可以使用类型直接调用