toString()
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student("张三", 100);
//Object 默认的toString方法没有用
//需要子类覆写 toString方法
System.out.println(student.toString());
//控制台打印对象时 toString可以忽略
System.out.println(student);
}
}
equals()
/**
* 比较name和age全相同就返回true
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
};
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return getAge() == student.getAge() && getName().equals(student.getName());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getAge());
}
Student student1 = new Student("李四", 88);
Student student2 = new Student("李四", 88);
//Object 默认equals的方法 用的时== 比较的时对象地址
boolean flag= student1.equals(student2);
System.out.println(flag);