Java: have to know the object class

The object class is the top-level parent class of all classes. Any object (except the basic type) implements the methods of the object class, including arrays.

1、 Equals

1. What's the difference between equals and = =?

We usually see a kind of question: what is the difference between = = and equals? Every time I see such a problem, I feel ambiguous. This time, I completely summarize a wave:

Starting from the equals method in the object class, let's look at its source code:

    public boolean equals(Object obj) {
        return (this == obj);
    }

In fact, in the object class, A. equals (b) is equivalent to a = = B, which determines whether two objects have the same reference.

We found that if two objects have the same reference, the equals result is equal. However, in most cases, such a judgment form is meaningless. In practice, we often need to use equals to detect the equality of object states and attributes, and often override the equals method in the class.

Let's take string as an example to see the source code in the string class:

    //重写注意形参类型必须是Object
    public boolean equals(Object anObject) {
        //引用相同,必然返回true
        if (this == anObject) {
            return true;
        }
        //判断anObject类型是否和String相同
        if (anObject instanceof String) {
            //anObject向下转型
            String anotherString = (String)anObject;
            int n = value.length;
            //每个位置上字符逐一比较
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

We can find that for two string objects, in addition to judging whether they are the same reference, we also compare whether the string values are equal (we will summarize the problems related to the address of the string later). The same example also includes wrapper classes such as integer. If you are interested, you can check the source code.

2. Specification of equals method

The equals method implements the equivalence relationship of non empty object references:

3. Instanceof and getclass()

If the equals method judges that both parties belong to the same class, it is easier to write code according to the above rules. However, if the two sides are different, we need to consider which way to judge the symmetry.

Let's see the difference between instanceof and getClass () through a small test:

public class EqualsDemo {
    public static void main(String[] args) {
        Super aSuper = new super();
        Sub sub = new Sub();
        System.out.println(sub.getClass() == aSuper.getClass());//false
        System.out.println(sub instanceof Super);//true
    }
}
class Super{}
class Sub extends Super{}

It can be found that when judging getClass, the types of subclasses and superclasses are strictly different; Instanceof means that the concept of parent class applies to all subclasses, the same class.

For a class to write equals:

4. Other summary

    int[] a = {1,2,3};
    int[] b = {1,3};
    System.out.println(Arrays.equals(a,b));//true

2、 Hashcode

The hashcode method at the bottom of object is modified natively, not written in Java language. We should know:

This method will return the hash code value of the object. The hash code is integer and irregular, also known as hash code.

We have previously conducted a jdk1 based Through the analysis of HashMap source code of 8, it is learned that the key value is transformed into integer hash value through hash function, and then it is mapped to each index of the array through ingenious operation. Using the advantage of fast array query, the performance is greatly improved.

1. Specification of hashcode

2. Hashcode implementation of string class

Hash functions are very diverse. We take the hashcode implementation of the common string class as an example:

    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

3、 ToString

This method returns the string representation of the object. The result should be a concise but informative representation for easy reading. It is recommended that all subclasses override this method.

If it is not rewritten, the form defined in the object class will be very unpleasant. Here is the tostring() source code:

    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

Return string = the name of the runtime class corresponding to the object + "@" + the unsigned hexadecimal representation of the object hash code

1. Print object information

We can try:

    public static void main(String[] args) {
        Super s = new super();
        System.out.println(s);
    }
    //输出结果
    com.my.objectClass.equals.Super@677327b6

System. out. println(s); It means standard output s to the printing table. Let's see the specific steps:

    public void println(Object x) {
        //首先调用String类的valueOf方法,获得s的字符串表现形式
        String s = String.valueOf(x);
        synchronized (this) {
            //打印
            print(s);
            //换行
            newLine();
        }
    }

Let's continue to see what valueof is about:

    public static String valueOf(Object obj) {
    //如果为null,则输出"null",非空则调用toString()
        return (obj == null) ? "null" : obj.toString();
    }

So far, we can know that when we try to print an object, we will call the toString method of the object. We can try to rewrite this method, so that we can locate it quickly and clearly during the test.

2. On elegant printing array

Array is also a special type. Through printing, we can find that its results are outrageous and strange. For specific rules, see the getname () method of class class in the official document.

    int[] arr = {1,3};
    System.out.println(arr);//[I@14ae5a5

In short, we always hope that what we print out is that the numbers in the array are arranged neatly, right.

We can use the static toString method of the arrays tool class to print arrays gracefully:

    public static String toString(int[] a) {
        if (a == null)
            return "null";
        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
            b.append(a[i]);
            if (i == iMax)
                return b.append(']').toString();
            b.append(",");
        }
    }

3. Custom toString method

Since it is user-defined, there are no strict regulations. In order to make the test data clearer, you can think of a suitable method for printing information.

Current ides generally support automatic generation of toString methods based on fields. For example, I use the idea, which can be generated quickly by pressing ALT and INS keys.

    
public class EqualsDemo {
    public static void main(String[] args) {
        System.out.println(new Person());
    }
}
class Person{

    String name = "天乔巴夏丶";
    int age = 18;

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

//测试结果
Person{name='天乔巴夏丶',age=18}

5、 Other important methods

So far, we have summarized three important methods in object, such as

These methods will be summarized later.

Reference: Java core technology Volume I

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>