In depth understanding of the Java core class library — objects class

Time:2021-11-29

1 Objects

1.1 objects method

Tool class, commonly used for checking operations

Return value Method name effect
static int checkFromIndexSize​(int fromIndex, int size, int length) Check whether the sub range [fromindex, fromindex + size) is within the range limit of [0, length).
static int checkFromToIndex​(int fromIndex, int toIndex, int length) Check whether the sub range [fromindex, toindex) is within the range limit of [0, length]
static int checkIndex​(int index, int length) Check whether the sub range index is within the limit of [0, length)
static int compare(T a, T b, Comparator<? super T> c) If the parameters a and B are the same, return 0; otherwise, return the result of c.compare (a, b)
static boolean deepEquals(Object a, Object b) Compare whether the parameters a and B are equal in depth (if a and B are arrays, compare each parameter of the array)
static boolean equals(Object a, Object b) Compare whether parameters a and B are equal
static int hash(Object… values) Generates a hash code for the sequence of input values
static int hashCode(Object o) Non null returns hash code, null throws NullPointerException
static boolean isNull(Object obj) The obj parameter is null and returns true
static boolean nonNull(Object obj) The obj parameter is not null and returns true
static T requireNonNull(T obj) Check that the specified object reference is not null. If it is null, a NullPointerException will be thrown
static T requireNonNull(T obj, String message) Check that the specified object reference is not null, otherwise a custom NullPointerException will be thrown
static T requireNonNull​(T obj, Supplier messageSupplier) Check whether the specified object reference is null. If so, throw a custom NullPointerException.
static T requireNonNullElse​(T obj, T defaultObj) If it is non null, the first parameter is returned; otherwise, the second non null parameter is returned.
static T requireNonNullElseGet​(T obj, Supplier<? extends T> supplier) If it is non null, the first parameter is returned; otherwise, the non null value supplier. Get () is returned.
static String toString(Object o) Returns the string representation of the object
static String toString(Object o, String nullDefault) If the first parameter is not null, the result of the first parameter calling toString is returned; otherwise, the second parameter is returned

1.2 common methods of objects

1.2.1 equals(Object a, Object b)

Equals (object a, object B) source code:
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}

1.2.2 isNull(Object obj)

Isnull (object obj) source code:
public static boolean isNull(Object obj) {
return obj == null;
}

1.2.3 nonNull(Object obj)

Nonnull (object obj) source code:
public static boolean nonNull(Object obj) {
return obj != null;
}

1.2.4 requireNonNull(T obj)

Requirenonnull (t obj) source code:
public static T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}

1.3 objects source code


package java.util;
import jdk.internal.util.Preconditions;
import jdk.internal.vm.annotation.ForceInline;
import java.util.function.Supplier;
public final class Objects {
    private Objects() {
        throw new AssertionError("No java.util.Objects instances for you!");
    }
    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }
    public static boolean deepEquals(Object a, Object b) {
        if (a == b)
            return true;
        else if (a == null || b == null)
            return false;
        else
            return Arrays.deepEquals0(a, b);
    }
    public static int hashCode(Object o) {
        return o != null ? o.hashCode() : 0;
    }
    public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }
    public static String toString(Object o) {
        return String.valueOf(o);
    }
    public static String toString(Object o, String nullDefault) {
        return (o != null) ? o.toString() : nullDefault;
    }
    public static <T> int compare(T a, T b, Comparator<? super T> c) {
        return (a == b) ? 0 :  c.compare(a, b);
    }
    public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }
    public static <T> T requireNonNull(T obj, String message) {
        if (obj == null)
            throw new NullPointerException(message);
        return obj;
    }
    public static boolean isNull(Object obj) {
        return obj == null;
    }
    public static boolean nonNull(Object obj) {
        return obj != null;
    }
    public static <T> T requireNonNullElse(T obj, T defaultObj) {
        return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
    }
    public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) {
        return (obj != null) ? obj
                : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()");
    }
    public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
        if (obj == null)
            throw new NullPointerException(messageSupplier == null ?
                                           null : messageSupplier.get());
        return obj;
    }
    @ForceInline
    public static
    int checkIndex(int index, int length) {
        return Preconditions.checkIndex(index, length, null);
    }
    public static int checkFromToIndex(int fromIndex, int toIndex, int length) {
        return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
    }
    public static int checkFromIndexSize(int fromIndex, int size, int length) {
        return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
    }
}

2 different from object

2.1 object construction method

public Object()

  • The object class is the base class, which isParent of all classes (base class)
  • If a class does not explicitly inherit a specific class, it willInherit object class by default

For example, we define a class:

public class Person{
}
In fact, it is used as follows:
public class Person extends Object{
}

  • Polymorphism of object: using object canReceive any reference data type

Example:

public static void main(String[] args){
	String text = "123";
	say(text);
	int a = 10;
	say(a);
	say("123");
}
Public static void say (object o) {// embodiment of polymorphism
	System.out.println(o);
}

2.2 other methods

Return value Method name effect
static int checkFromIndexSize​(int fromIndex, int size, int length) Check whether the sub range [fromindex, fromindex + size) is within the range limit of [0, length).
static int checkFromToIndex​(int fromIndex, int toIndex, int length) Check whether the sub range [fromindex, toindex) is within the range limit of [0, length]
static int checkIndex​(int index, int length) Check whether the sub range index is within the limit of [0, length)
static int compare(T a, T b, Comparator<? super T> c) If the parameters a and B are the same, return 0; otherwise, return the result of c.compare (a, b)
static boolean deepEquals(Object a, Object b) Compare whether the parameters a and B are equal in depth (if a and B are arrays, compare each parameter of the array)
static boolean equals(Object a, Object b) Compare whether parameters a and B are equal
static int hash(Object… values) Generates a hash code for the sequence of input values
static int hashCode(Object o) Non null returns hash code, null throws NullPointerException
static boolean isNull(Object obj) The obj parameter is null and returns true
static boolean nonNull(Object obj) The obj parameter is not null and returns true
static T requireNonNull(T obj) Check that the specified object reference is not null. If it is null, a NullPointerException will be thrown
static T requireNonNull(T obj, String message) Check that the specified object reference is not null, otherwise a custom NullPointerException will be thrown
static T requireNonNull​(T obj, Supplier messageSupplier) Check whether the specified object reference is null. If so, throw a custom NullPointerException.
static T requireNonNullElse​(T obj, T defaultObj) If it is non null, the first parameter is returned; otherwise, the second non null parameter is returned.
static T requireNonNullElseGet​(T obj, Supplier<? extends T> supplier) If it is non null, the first parameter is returned; otherwise, the non null value supplier. Get () is returned.
static String toString(Object o) Returns the string representation of the object
static String toString(Object o, String nullDefault) If the first parameter is not null, the result of the first parameter calling toString is returned; otherwise, the second parameter is returned

2.2.1 equals(Object obj)

Equals (object obj) source code:
public boolean equals(Object obj) {
return (this == obj);
}

  • The equals method implements equivalence on non null object references
  • be equal to
    • For any non null reference values X and y, this method returns true if and only if x and Y refer to the same object (x = = y has the value true)
  • ==Compared to the memory address
  • Note that it is often necessary to override the hashcode method when overriding this method in order to maintain the general contract of the hashcode method, which declares that equal objects must have equal hash codes.
public static void main(String[] args) {
        Person P = new person (1234, "Zhang San");
        Person e = new person (2345, "Li Si");
        System.out.println("p:"+p.hashCode());//p:1239731077
        System.out.println("e:"+e.hashCode());//e:357863579
        System.out.println(p.equals(e));//false
        e=p;// At this time, it points to the same memory address
        System.out.println("e:"+e.hashCode());//e:1239731077
        System.out.println(p.equals(e));//true
}

Output results:
p:1239731077
e:357863579
false
e:1239731077
true

Five features when overriding the equals method:

Reflexivity: X. equals (x) should return true for any non empty reference value X.
Symmetry: for any non null reference values X and y, x.equals (y) should return true if and only if y.equals (x) returns true.
Transitivity: for any non null reference values x, y, and Z, if x.equals (y) returns true and y.equals (z) returns true, x.equals (z) should return true.
Consistency: for any non null reference values X and y, multiple calls to x.equals (y) always return true or false, provided that the information used in the equals comparison on the object is not modified.
Nonempty: x.equals (null) should return false for any nonempty reference value X.

2.2.2 toString()

Tostring() source code
public String toString() {
return getClass().getName() + “@” + Integer.toHexString(hashCode());
}

The default is string. Usually, a string representing the object in text is returned, and the memory address of the object is returned (the class name of the object instance @ the unsigned hexadecimal of the hash code of the object, that is: getclass(). Getname() + ‘@’ + integer. Tohexstring (hashcode()))

public static void main(String[] args) {
        Person P = new person (1234, "Zhang San");
        Person e = new person (2345, "Li Si");
        System.out.println("e.getClass():"+e.getClass());
        System.out.println("e.hashCode():"+e.hashCode());
        System.out.println("e.toString():"+e.toString());
}

Output results:
e.getClass():class com.company.demo.Person
e.hashCode():114132791
e.toString():com.company.demo.Person@6cd8737

  • It is recommended to override the toString method in object

2.3 object source code


package java.lang;
import jdk.internal.HotSpotIntrinsicCandidate;
public class Object {
    private static native void registerNatives();
    static {
        registerNatives();
    }
    @HotSpotIntrinsicCandidate
    public Object() {}
    @HotSpotIntrinsicCandidate
    public final native Class<?> getClass();
    @HotSpotIntrinsicCandidate
    public native int hashCode();
    public boolean equals(Object obj) {
        return (this == obj);
    }
    @HotSpotIntrinsicCandidate
    protected native Object clone() throws CloneNotSupportedException;
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    @HotSpotIntrinsicCandidate
    public final native void notify();
    @HotSpotIntrinsicCandidate
    public final native void notifyAll();
    public final void wait() throws InterruptedException {
        wait(0L);
    }
    public final native void wait(long timeoutMillis) throws InterruptedException;
    public final void wait(long timeoutMillis, int nanos) throws InterruptedException {
        if (timeoutMillis < 0) {
            throw new IllegalArgumentException("timeoutMillis value is negative");
        }
        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }
        if (nanos > 0) {
            timeoutMillis++;
        }
        wait(timeoutMillis);
    }
    protected void finalize() throws Throwable { }
}

summary

That’s all for this article. I hope it can help you and pay more attention to developeppaer!