Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there difference between arr.equals(anotherArr) and arr == anotherArr?

Any array in java is Object. hence it has equals method. But I cannot watch realization of this method(or maybe is it possible ?)

I wrote several examples and always == and equals returns similar results.

Is there way when == and equals return different results ?

like image 522
gstackoverflow Avatar asked Dec 19 '25 14:12

gstackoverflow


2 Answers

There is difference

1)

int[] a1 = {};
long[] a2 = {};
boolean r1 = a1.equals(a2);  // returns false
boolean r2 = a1 == a2;       // compile time error

2)

int[] a1 = null;
int[] a2 = {};
boolean r1 = a1.equals(a2);  // throws NPE
boolean r2 = a1 == a2;       // returns false
like image 83
Evgeniy Dorofeev Avatar answered Dec 21 '25 02:12

Evgeniy Dorofeev


I don't think so this is the equalsmethod :

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

And it internally uses == operator for comparison.

You can view the javaDoc here.

like image 34
Runcorn Avatar answered Dec 21 '25 02:12

Runcorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!