Java – comparison of two empty objects of two different types

public void m1(Integer f) {
public void m1(Integer f) {
    ...
}

public void m1(Float f) {
    ...
}

public void main() {
    m1(null); // error: the method m1(Integer) is ambiguous for the type Main
    m1((Integer) null); // success
}

Given the above example, we can admit that null was entered in some ways So why does the following line print true? Of course, both O1 and O2 have no value (i.e. null), but they are not of the same type (integer vs float) First of all, I think there will be printing errors

Integer i = null;
Object o1 = (Object) i;
Float f = null;
Object o2 = (Object) f;
System.out.println(o1 == o2); // prints true

// in short:
System.out.println(((Object) ((Integer) null)) == ((Object) ((Float) null))); // prints true

Solution

All null values are untyped and equal You can pass it to different reference types, but it makes no difference for comparison purposes

It is not a null value typed, but a reference to nulls that can be typed

A common question is what happened here

class A {
    public static void hello() { System.out.println("Hello World"); }

    public static void main(String... args) {
        A a = null;
        a.hello();
        System.out.println("a is an A is " + (a instanceof A)); // prints false.
    }
}

The compiler treats the type of a as a, so it calls a static method But the referenced value is null and has no type

The only thing you can do with null without causing a NullPointerException is to assign or pass it without checking it or comparing it to another reference

BTW

In short: the compiler will select the method according to the type of reference, and execute the class based on the referenced object at run time At runtime, null is treated as any type or no type, and if you try to dereference it, you get a NullPointerException

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
分享
二维码
< <上一篇
下一篇>>