Rajesh Vyas Rajesh Vyas - 4 months ago 12x
Java Question

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.


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.)