toString
原本作用
- 返回对象的字符串表示形式
- 包名类名+@+对象地址值
System.out.println(obj);
也会打印这样的地址值
源码:
public void println(Object x) {
String s = String.valueOf(x);
if (getClass() == PrintStream.class) {
// need to apply String.valueOf again since first invocation
// might return null writeln(String.valueOf(s));
} else {
synchronized (this) {
print(s);
newLine();
}
}
}
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
如果不是null,就会toString
一般重写toString
- 如果我们打印一个对象的属性值的话,那么重写toString()就行了,在重写方法时,把对象的属性拼接
equals
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
boolean equals = s1.equals(s2);
System.out.println(equals);
}
//false
重写equals后运行结果为true
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public static void main(String[] args) {
String s = "abc";
StringBuilder sb = new StringBuilder("abc");
System.out.println(s.equals(sb));
System.out.println(sb.equals(s));
//运行结果
//false false
}
第一个中调用对象是String,先看是不是同一个对象,如果不是字符串,直接返回false
第二个中调用对象时StringBuilder,StringBuilder没有重写equals方法,Object中使用的是==
比较两个对象的地址值
clone
重写对象的clone方法
方法会在底层帮我们创建一个对象,并把原对象的数据拷贝过去
细节:
- 重写Object中的clone方法
- 让Javabean类实现Cloneable
- 创建原对象并调用clone就可以了
Objects
equals
可以规避调用者为null的判断
Student s1=null;
Student s2=new Student();
boolean equals = Objects.equals(s1, s2);
System.out.println(equals);
//false
isNull
判断对象是否为null,如果为null,返回true
Student s3 = null;
Student s4 = new Student();
System.out.println(Objects.isNull(s3));//true
System.out.println(Objects.isNull(s4));//false
nonNull
System.out.println(Objects.nonNull(s3));//false
System.out.println(Objects.nonNull(s4));//true