Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it possible to compare incompatible types by reference in Java?

Check out this snippet:

    List<Integer> c = new ArrayList<>();
    Map<String,Boolean> m = new HashMap<>();
    if( c == m ) //no error here!  WHY?
    {
        c = m; //"Incompatible types" error, as expected.
        m = c; //"Incompatible types" error, as expected.
    }

How come c == m gives no error?

I am using the javac of jdk1.8.0.20 and I have no reason to suspect that it disregards the java language specification, so this is with a fairly absolute level of certainty in the spec, so:

What is the point / purpose / usefulness of having something like this allowed by the spec?

like image 970
Mike Nakis Avatar asked Feb 27 '15 15:02

Mike Nakis


1 Answers

Just because the types are inconvertible doesn't mean that are not equal objects. If the types are "Inconvertible" it means a cast is required to check the type is actually convertible.

interface Outputer extends Consumer<String>, Serializable { }

Outputer out = System.out::println;
Consumer<String> cs = out;
Serializable s = out;
System.out.println(s == cs); // prints true

// s = cs; // Inconvertible types, doesn't compile
s = (Serializable) cs; // compiles and runs fine.

cs and s are inconvertible types, yet they point to the same object and this prints true

like image 138
Peter Lawrey Avatar answered Sep 28 '22 02:09

Peter Lawrey