tostring方法,equal方法,hashcode方法,只适用于只有基本数据类型的类,如果还有引用类型,则不适用,因为此时只会比较引用层面,而不是引用所指向的数据。
自动生成的clone方法一定需要重写。
注意:自动生成的hashcode方法可能生成负数,因为调用了native方法,所以如果为负数,则需要取正。
可以这样处理:
package com.liuheizi.demo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
/**
* @ Author : LHZ
* @ Data : Created in 9:46 2021/9/19
* @ Description: TODO
* @ Version : 1.8
*/
class B{
int b;
public B(int b) {
this.b = b;
}
}
class A {
int a;
B c;
public A(int a, B c) {
this.a = a;
this.c = c;
}
@Override
public String toString() {
return "A{" +
"a=" + a +
", c=" + c +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A a1 = (A) o;
return a == a1.a &&
Objects.equals(c, a1.c);
}
@Override
public int hashCode() {
return Objects.hash(a, c);
}
}
public class TestDemo6 {
public static void main(String[] args) throws CloneNotSupportedException {
B b1 = new B(1);
B b2 = new B(1);
A a1 = new A(3, b1);
A a2 = new A(3, b2);
System.out.println(a1.hashCode());
System.out.println(a2.hashCode());
System.out.println(a1.hashCode()==a2.hashCode());
System.out.println(a1.equals(a2));
System.out.println(a1.toString());
}
}
带引用自动生成的toString方法: