equal

B

Bob

Jerry said:
Does o1.equals(o2) imply o1==o2?

No, not necessarily.

a.equals(b) is a test for meaningful equivalence.

a == b is a test for the memory address of a against the memory address
of b. I.e. are a and b one object in memory?
 
R

Ross Bamford

Does o1.equals(o2) imply o1==o2?

Try it:

public static void main(String[] args) {
String s1 = new String("A string");
String s2 = new String("A string");
System.out.println("equals : "+s1.equals(s2)); // prints 'true'
System.out.println("identity: "+(s1 == s2)); // prints 'false'
}

So, no.

As an aside, if you use string literals for this then you will get see
true for both println statements, which demonstrates the string pooling
used by the JVM. You can see the same effect by 'internalising' the
strings as you create them.

String s1 = new String("A string").intern();
String s2 = new String("A string").intern();

s1 and s2 will reference the same object.
 
H

Harald

Does o1.equals(o2) imply o1==o2?

No, not at all: just because two things looks the same (equals()) they
need not be identical (==).

The other way round should better be true, however. Buggy
implementations of equals() may exist though.

Harald.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top