Rajesh Vyas
Rajesh Vyas

Reputation: 161

Java == operator works for list and set comparison but gives compile time error for String and StringBuilder comparison

List<String> list = new ArrayList<String>();
    Set<String> set = new HashSet<String>();
    if(list == set) {

    }
    String str = "test";
    StringBuilder stringBuilder = new StringBuilder(); 
    if(str == stringBuilder){

    }

In above code list and set comparison doesn't give compile time error. So why does str and stringBuilder doesn't compile.

Upvotes: 2

Views: 226

Answers (1)

Stephen C
Stephen C

Reputation: 718718

This is the intuitive explanation.

A List can be compared to a Set using ==, because there could be classes whose instances are both lists and sets.

A String cannot be a compared to a StringBuilder using == because an object that is both a String and a StringBuilder is impossible.


However if you wanted to be able to compare String and StringBuilder using == you could do this:

String str = "test";
CharSequence chars = new StringBuilder(); 
if (str == chars) {
    // ...
}

Obviously, the above test will evaluate to false. But it will compile.

This is legal because the type system says that chars could be a String. Note that CharSequence is a supertype of String and StringBuffer. (In this case, the supertype is an interface, but it doesn't need to be an interface.)


(Notes for other people encountering this question and wondering what the code is "trying to do" ... and the right way to do it.

  1. It makes no sense to compare a HashSet and an ArrayList using ==. The == operator tests object identity, and no HashSet and ArrayList can ever be the same object.

  2. It makes no sense to use equals(Object) either. The javadocs state that a list can only be "equal" to another list. Besides, comparing an explicitly ordered collection with an collection where the ordering is unstable is ... nonsensical.

  3. The same applies to String versus StringBuffer. They can never be == and they can never be equal according to equals(Object). If you wanted to compare a string and a string buffer character-wise, the simple answer would be string.equals(stringBuffer.toString()).

In short. The code makes almost no sense ... except as an illustration of the OP's real question about how the typing works.)

Upvotes: 9

Related Questions