Search code examples
javaequalsjava-threads

Why isn't equals() method working on Threads?


public class Test {
    public static void main(String[] args) {
        Thread t1 = new Thread();
        Thread t2 = new Thread();
        Thread t3 = t1;

        String s1 = new String();
        String s2 = new String();

        System.out.println(t1 == t3);  //true
        System.out.println(t1 == t2);  //false

        **System.out.println(t1.equals(t2));  //false**
        System.out.println(s1.equals(s2)); //true
    }
}

As we know, Object.equals() method is used for checking the content rather than the reference. So when you create two threads and perform equals() on them, what exactly is happening?

I assumed threads work differently. (I'm a beginner)

How do they work?


Solution

  • You seem to misunderstand what equals does.

    I suppose that you learned that equals can be used to compare strings on a character by character basis instead of comparing them by their references. Then you thought, okay, so equals can compare stuff like that!

    And then, you thought that these two threads are the same:

    Thread t1 = new Thread();
    Thread t2 = new Thread();
    

    "because look! They are created the same way - with new Thread(). So they should be equal!" you thought.

    However, equals does not think the two threads are equal. In fact, Thread does not even override equals (String does)! Therefore, it uses the equals implementation from its superclass, Object, which compares the references.

    Therefore, equals is not like some "magical" thing that compares objects "logically". It has to be overridden in subclasses. It does not always work where you want it to.

    Another example would be Scanner, which does not override equals either.

    Scanner s1 = new Scanner("Hello");
    Scanner s2 = new Scanner("Hello");
    System.out.println(s1.equals(s2)); // false
    

    s1 and s2 has exactly the same string to scan and they are at exactly the same position of the string, yet they are not equal when you compare them with equals.