Commonly used methods in Javase | Object class

equals(object obj) method:

equals(object obj) meaning
  • The default equals method compares whether the reference addresses of two objects are equal, rather than comparing specific values. If you want to compare whether the values/contents in two objects are equal, you must override the equals() method.
  • However, many Java classes (such as String , Integer , etc.) have overridden the equals() method. At this time, equals() compares two objects.
  • In Java, a reference to an object is an address value that points to the location of the object in memory. Through a reference, we can access and manipulate the object.
equals(object obj) source code
public boolean equals(Object obj) {
    
        
return (this == obj);
}
equals(object obj) example
public class Test() {
    
    

    //在普通的对象中时,equals()方法比较的是对象的引用(比较对象间的地址值)是否相等
    static class Student1 {
    
    
        String name = "张三";
        int age = 18;
    }

    static class Student2 {
    
    
        String name = "张三";
        int age = 18;
    }

    static class Student3 {
    
    
        String name = "李四";
    }


    public static void main(String[] args) {
    
    
        Object str1 = "Hello World";
        Object str2 = "Hello World2";
        Object str3 = str1;
        Object str4 = "Hello World";
		// 在String、Integer等时,equals()方法已被重写,此时比较的是对象的内容
        System.out.println(str1.equals(str2)); //false
        System.out.println(str1.equals(str3)); //true
        System.out.println(str1.equals(str4)); //true

        System.out.println("----------------------------");
        Student1 s1 = new Student1();
        Student2 s2 = new Student2();
        Student3 s3 = new Student3();
        //比较的是两个对象的引用(可理解为: 地址值),就算值相等,地址值一般也不会相等的
        System.out.println(s1.equals(s2)); // false 
        System.out.println(s1.equals(s3)); //false
        //要判断对象的内容是否相等,要重写equals()方法
    }
}
Override equals(object obj) method

Override the equals() method: determine the content of the object

public class Student {
    
      //重写equals()方法,通过该方法来判断两个对象的内容是否相等
    private String name;
    private int age;

    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
    
     //传入一个要判断的对象
        if (this == obj) {
    
     //如果两个对象引用相等,表明是同一个对象,对象的内容自然也相等
            return true;
        }

        //如果obj为null 或 两个对象的类都不同,那么对象的内容自然也是不相同
        if (obj == null || getClass() != obj.getClass()) {
    
    
            return false;
        }

        //将obj对象进行类型转换,然后进行对象的内容的判断
        Student student = (Student) obj;
        return age == student.age && Objects.equals(name, student.name);          	    	 	//Objects.equals()比较的是对象的内容
    }

      public static void main(String[] args) {
    
    
        Student student1 = new Student("张三",18);
        Student student2 = new Student("张三",20);
        Student student3 = new Student("张三",18);

        //如果用默认的equals()方法判断,那么这三个对象都不相等,重写后则 student1与 student3相等
        System.out.println(student1.equals(student2));  //false
        System.out.println(student1.equals(student3));  //true
    }
}

hashCode() method:

The meaning of hashCode()
  • The default hashCode() method is used to generate an integer representation of the hash code for the object.
  • The object's hash code is calculated using a hash function. The hash function takes into account the internal state and contents of the object in order to generate different hash codes for different objects.
  • When we need to use hash table data structures (such as HashMap, HashSet), etc. The hash table uses the hash code of the object to determine the location of storage and search. The search efficiency can be improved through reasonable hash code distribution .
  • It is important to note that different objects may return the same hash value, which is known as a hash collision .
  • In Java, if you override equals()methods, then you should also override hashCode()methods to keep them consistent. This is because the Java specification requires that equal objects must have equal hash values.
hashCode() source code
  public native int hashCode();
hashCode() example
public class Test {
    
    

    public static class Student1 {
    
     

    }

    public static class Student2 {
    
    

    }
    
    public static void main(String[] args) {
    
    
        Student student = new Student();
        Student2 student2 = new Student2();

        //两个不通过的对象的哈希码是不一样的
        System.out.println(student.hashCode());  //668386784
        System.out.println(student2.hashCode()); //668386784
        //
        System.out.println(student.hashCode()==student2.hashCode()); // faslse

    }
}

Why should we rewrite the hashCode() method after overriding the equals() method?
  • If you override the equals( ) method, you should also override the `` method to keep them consistent. This is because the Java specification requires that equal objects must have equal hash values.
  • If two objects are equal according to the equals() method, then their hash codes (returned by the hashCode() method) should be the same. This is because hash codes are often used to quickly find objects in data structures such as hash tables. If equal objects return different hash codes, this may result in incorrect behavior.
Override hashCode() method
public class Person {
    
    
    private String name;
    private int age;

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    //此处应重写equals()方法,但为节省代码量就不写了....,可看重写equals()篇

    @Override //根据对象的属性值计算出一个哈希码,以确保相等的对象具有相等的哈希码。
    public int hashCode() {
    
    
        // 定义一个常量prime,它是一个质数(通常选择一个质数可以保持哈希码的均匀分布)
        final int prime = 31;  
        int result = 1;  //result变量存储最终的哈希码
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    public static void main(String[] args) {
    
    
        Person person1 = new Person("张三", 20);
        Person person2 = new Person("张三", 20);

//上面两个对象如果重写了equals()方法,那返回值是true,此时也要重写hashCode()方法以确保两个对象的哈希码是一样的
        System.out.println(person1.hashCode()); // 776470
//两个对象的哈希码是一样的,这是重写了hashCode的功劳,也符合Java规则,因为重写了equals方法后对象一样,哈希码也要一样
        System.out.println(person2.hashCode()); //776470
    }
}

getClass() method:

The meaning of getClass()
  • getClass() is used to return the runtime class of the object.
  • The return value of getClass() is a Class object, which can be used to call various methods to obtain information about the class.
getClass() source code
@HotSpotIntrinsicCandidate
public final native Class<?> getClass();
getClass() example
public class Test {
    
    

    public static class MyClass {
    
    
        private int value;

        public MyClass(int value) {
    
    
            this.value = value;
        }
        

        //输出信息的方法
        public void printInfo() {
    
    
            System.out.println(value);
        }
    }

    public static void main(String[] args) throws
            NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    
    

        MyClass myClass1 = new MyClass(10);
        MyClass myClass2 = new MyClass(20);

        //获得类对应的Class类
        //使用 getClass()获得运行中的MyClass (获得Class类)
        Class<?> class1 = myClass1.getClass();
        Class<?> class2 = myClass2.getClass();
        //获得类名
        System.out.println(class1.getName());  // Test$MyClass
        System.out.println(class2.getName());  // Test$MyClass



        //获得方法对应的Method类
        Method printInfo_myClass1 = class1.getMethod("printInfo"); //返回一个Method类
        Method printInfo_myClass2 = class2.getMethod("printInfo");
        //调用类中方法
        // invoke()方法是Method类提供的一个方法,调用该类中的方法
        printInfo_myClass1.invoke(myClass1);    //方法输出: 10
        printInfo_myClass2.invoke(myClass2);   //方法输出: 20
        
    }
}

toString() method:

The meaning of toString()
  • The default toString() method is used to convert the object to string form.
  • In Java, if a class does not override the toString() method, then the toString() method of the class will return the hexadecimal string representation of the class name and the hash code of the class. If we want to print the contents of the object returned when printing the object, we need to override the toString() method at this time.
  • We can customize the representation of strings based on the object's attribute values ​​and needs.
  • For example, for a Personclass, we could override toString()methods to return a string representation containing the object's attributes, such as name and age.
toString() source code
  • getClass().getName(): Get the class name of the runtime class
  • Integer.toHexString: A string used to convert an integer to hexadecimal
  • hashCode(): Generate an integer hash code for the object
  • Integer.toHexString(hashCode()); : Hexadecimal string representation of hash code
  • return getClass().getName() + “@” + Integer.toHexString(hashCode()); :
    Returns a hexadecimal string representation containing the object class name and hash code
public String toString() {
    
        
 return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

toString() example
public class Person {
    
    
    public static void main(String[] args) {
    
    
        
        Person person = new Person();
        //输出的默认的toString()方法的内容:  类名+@+哈希码的十六进制字符串表现形式
        System.out.println(person); //Person@16b98e56
    }


Override toString() method
public class Person {
    
    
    private String name;
    private int age;

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    
    public static void main(String[] args) {
    
    
        Person person = new Person("王五",21);
        System.out.println(person); // 打印的是: Person{name='王五', age=21}
        //如果不用重写toString方法,那打印的就是 类名+@+哈希码的十六进制字符串表示形式
    }
}

clone() method:

The meaning of clone()
  • clone( ): Creates and returns a copy of this object.
  • To use the clone() method, it requires that the target class must implement the cloneable interface.
  • The default clone() is a shallow copy, that is, when copying an object, the new object and the original object share the same internal object reference. This means that for properties of reference types, the copy and the original object will refer to the same object instance.
clone() source code
protected native Object clone() throws CloneNotSupportedException;
clone() example
public class MyClass implements Cloneable {
    
    
    private int id;
    private String name;

    public MyClass(int id, String name) {
    
    
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
    
    
        return "MyClass{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public static void main(String[] args) throws CloneNotSupportedException {
    
    
        MyClass class1 = new MyClass(1, "张三");
        MyClass class2 = (MyClass) class1.clone();
        System.out.println(class1); // MyClass{id=1, name='张三'}
        System.out.println(class2); // MyClass{id=1, name='张三'}
    }
}

Guess you like

Origin blog.csdn.net/m0_70720417/article/details/132156834