Object类
toString()与equals()
public class object {
public static void main(String[] args) {
student s1=new student("张三",19);
//默认的object类的tostring方法返回的是包名+类名+哈希16进制值
//但tostring方法的实质是想要看内容,所以要重写
System.out.println(s1.toString());
System.out.println(s1);
student s2=new student("张三",19);
//object类的默认equals方法比较的是地址是否相同,但我们想要的是内容是否一致,所以重写该方法
System.out.println(s2.equals(s1));
}
}
class student{
private String name;
private int age;
//此处省略相应的get、set方法
/*
调用该方法者this=s2
传入的参数o=s1
*/
@Override
public boolean equals(Object o) {
//1、判断当前对象与参数的地址是否一致,一致返回true
if (this == o) return true;
//2、判断所传参数是否为null或者两者的类型是否一致
if (o == null || getClass() != o.getClass()) return false;
//3、代表所传参数与this的类型一致,进行强转
student student = (student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public String toString() {
return "student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
clone()对象克隆,简单了解即可
浅克隆
对于浅克隆,都是直接将原来的地址拷贝过来
//必须实现Cloneable接口
public class student implements Cloneable{
private String name;
private int age;
private double[] scores;//引用数据类型
public student() {
}
public student(String name, int age,double[] scores) {
this.name = name;
this.age = age;
this.scores=scores;
}
//此处省略相应的get、set方法
/*
要想实现克隆,必须重写clone方法,并且该类也要实现Cloneable接口,
该接口为标记接口(即接口内无方法)
*/
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class test {
public static void main(String[] args) throws CloneNotSupportedException {
student s1=new student("张三",19,new double[]{89,92.5});
//克隆后强制转换
student s2 =(student) s1.clone();
//查看信息是否一致,可看到对于引用数据类型,浅克隆只是拷贝了原地址
System.out.println(s1.getName());
System.out.println(s1.getAge());
System.out.println(s1.getScores());
System.out.println(s2.getName());
System.out.println(s2.getAge());
System.out.println(s2.getScores());
}
}
深克隆
对于引用数据类型,不会拷贝原来的地址,而是创建一个新的对象
代码中不同的是:
/*
要想实现克隆,必须重写clone方法,并且该类也要实现Cloneable接口,
该接口为标记接口(即接口内无方法)
*/
@Override
protected Object clone() throws CloneNotSupportedException {
//super去调用父类object中的clone方法
student s1=(student)super.clone();
s1.scores=s1.scores.clone();
return s1;
}
objects类
**这里只说明equals,其他的好理解 **
public class test {
public static void main(String[] args) throws CloneNotSupportedException {
student s1 = new student();
student s2 = new student();
//不使用工具类objects时,调用equals方法的对象不能为null,否则报空指针异常
System.out.println(s1.equals(s2));
//使用工具类objects时,则不存在上述问题
System.out.println(Objects.equals(s1, s2));
}
}