- 在java中,只有基本类型不是对象,例如:数值,字符,布尔类型
- 所有的数组类型,不管是对象数组还是基本数组都扩展了Object类
package hjx.com.test;
import org.junit.Test;
public class test12 {
@Test
public void test1(){
Object obj;
obj=new int[10];
System.out.println(obj);
System.out.println("====");
obj=new t12[10];
System.out.println(obj);
}
}
class t12{
}
运行结果
[I@22927a81 ==== [Lhjx.com.test.t12;@78e03bb5 Process finished with exit code 0equals方法
- Object类中的方法用于检测一个对象是否对于另一个对象。即判断两个对象的引用是否相等
- 实际应用中,如果两个员工的姓名,薪水和雇佣日期是一样的,就认为它们是相等的。此时再用equals方法,需要我们复写该方法
package hjx.com.test;
import java.util.Objects;
public class Employee {
private String name;
private double salary;
private String hireDay;
@Override
//注意这里的参数类型是Object,不是其他的(达不到复写效果)
public boolean equals(Object o) {
if(this==o){ //同一个引用对象
return true;
}
if(o==null || o.getClass()!=getClass() ){ //不是同一个类
return false;
}
Employee other = (Employee) o; //同一个类或者继承关系
// return salary==other.salary && name.equals(other.name) && hireDay.equals(other.hireDay);
return Objects.equals(salary,other.salary) &&
Objects.equals(name,other.name) && Objects.equals(hireDay,other.hireDay);
}
@Override
public int hashCode() {
return Objects.hash(name, salary, hireDay);
}
}
idea默认复写
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Double.compare(employee.salary, salary) == 0 && Objects.equals(name, employee.name) && Objects.equals(hireDay, employee.hireDay);
}
在子类定义equals方法时,首先调用超类的equals(已复写equals方法)。如果检测失败,对象就不可能相等。如果超类的字段相等,就需要比较子类的实例字段
public class Manager extends Employee{
....
public boolean equals(Object otherObject){
if(!super.equals(otherObject)){
return false;
}
Manager other(Manager)otherObject;
return bonus==other.bonus; //子类字段
}
}
两个double数怎么比较大小
- static int compare(double d1,double d2)
- Double有方法euqals(Double) 返回boolean
- int compareTo(Double anotherDouble)对两个 Double 对象所表示的数值进行比较。
- Objects.equals(Object a,Object b)
- static boolean equals(Object a,Object b) 如果a和b都为null,返回true;如果其中之一为null,返回false;否则返回a.equals(b)
- ==



