Java basics (Tostring () and equals ())

1. Override ToString () method

Object's toString () method helps us return a string whose format is fixed: class name @hashcode.

  • Role: Returns a string representation of the object. The data by default is meaningless to us, and it is generally recommended to override this method.
  • Case:
  • package day0528;
    //所有类都默认继承object类
    public class demo2 {
        public static void main(String[] args) {
             Student student=new Student();
            student.age=18;
            student.name="yyy";
            student.sex="女";
            System.out.println(student.toString());
        }
    }
    class Student{
        String name;
        String sex;
        int age;
    
        //重写ToString方法,在方法里面,打印所有属性的值
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", sex='" + sex + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

 

2. Override equals () method

  • Role: Used to compare whether two objects are the same

note:

           The first thing when rewriting equals is to determine whether a given object is of the same type as the current object. If it is not the same type, it directly returns false, which is not comparable. Before equals comparison, security verification is required to ensure that the given object is not null. If obj is null, it means that the reference variable does not point to any object, then you cannot reference the property or method of the object pointed to by obj (because the object does not exist) Doing will cause NullPointerException, null pointer exception!

  • Case:
package day0528;
//重写equals方法
public class demo3 {
    public static void main(String[] args) {
        Student1 s1=new Student1("yyy",18);
        Student1 s2=new Student1("yyy",18);
        Student1 s3=new Student1("wtc",18);
        System.out.println("s1.equals(s2)"+s1.equals(s2));
        System.out.println("s1.equals(s3)"+s1.equals(s3));
    }
}
class Student1{
    String name;
    int age;
    public Student1(String name,int age){
        this.name=name;
        this.age=age;
    }
    @Override
    public boolean equals(Object obj){
        if(this==obj){
            return true;
        }
        if(!(obj instanceof Student1)){
            return false;
        }
        Student1 objStudent=(Student1)obj;
        if(this.name.equals(objStudent.name) && this.age==objStudent.age){
            return true;
        }
        return false;
    }
}

 

Published 75 original articles · praised 164 · 110,000 views

Guess you like

Origin blog.csdn.net/qq_41679818/article/details/90678329