Skip to main content

Warning for "a" == "b"

6 replies [Last post]
Joined: 2003-06-20

Occaisionally I, or one of my colleagues, has (by mistake) compared strings or objects using == instead of .equals(). It would be nice (I think) if -Xlint gave a warning about this.

If you really want to compare objects in this way (and there may be some cases where you do), you could always write:

System.identityHashCode("a") == System.identityHashCode("b")

But I think this is usually not what the programmer intended.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-03-04

I found that I have this habit of comparing with equalsIgnoreCase instead of equals.

Eg for a parameter String s, up the top of my method you would often see:

if (s.equalsIgnoreCase("")) {

I find myself wondering how 'efficient' that is. Anybody have any thoughts on that?

Joined: 2004-11-26

Also, please keep in mind that is possible (and perhaps preferable) to correctly compare interned Strings in this way:

"a".intern() == "a".intern()

Joined: 2003-08-22

I think this is a classic beginner's mistake. Programmers should be educated about object identity before writing a lot of Java code. I don't think it is necessarily a flaw in the language.

The main annoyance is that you can't do 1.equals(2) and be consistent throughout...

Joined: 2003-06-10

OK, maybe the compiler can generate warnings, when Strings are compared with ==.

But we often compare (other) objects (e.g. type-safe enums) with == and do not want to get a warning for this useful code.

BTW, if you would use a decent IDE (e.g. IntelliJ IDEA), you would get such warnings upon request.


Joined: 2003-06-10

System.identityHashCode is NOT guaranteed to return a unique value for every Object. Therefore

System.identityHashCode(a) == System.identityHashCode(b)

can not be assumed to return the same result as

a == b

For example consider what happens in a 64 bit JVM where there are more than 2^32 objects. In this case some different objects will inevitably have the same identity hash code.

Joined: 2003-06-20

There are a number of good points made in the replies..

1) System.identityHashCode() is not adequate: Perhaps a method called System.isSameObject(Object o1,Object o2) could be added.

2) Want to keep == for enums: Yup. There would have to be a way to turn off the warning for enums, possibly other objects. That could be done with a meta tag, or marker interface. I'm tempted to suggest that it only becomes a warning if an equals method exists -- except that class Enum defines an equals() method (which does nothing but do an == comparison. Seems to just be there to make the method final.)

3) This is a novice error: That's what I used to think. But I've seen this error crop up in code by seasoned programmers from time to time. And perhaps you inherit a codebase that mistakenly uses == instead of .equals().