Using the equals() method with String and Object in Java

后端 未结 7 584
情话喂你
情话喂你 2021-02-02 03:11
Object o1 = new Object();
Object o2 = new Object();
//o1=o2;
System.out.println(o1.equals(o2));

It returns false. It can return true

相关标签:
7条回答
  • 2021-02-02 03:57

    == compares addresses of the objects / strings / anything

    .equals() designed to use internal state of the objects for comparison.

    So:

    new Object() == new Object() => false - two separate object at different addresses in memory.

    new String("a") == new String("a") => false - the same situation - two separate addresses for the string objects.

    new String("a").equals(new String("a")) => true - addresses differ, but Java will took one object state ('a') and compared with other object state ('a') will found them equal and will report true.

    Using the equals() method you can code the comparison any way is proper for your program.

    intern() is a bit different story. It is intended to return same object (address) for the same char sequence. It is useful to reduce amount of memory required when you have same strings constructed several times.

    new String("aaa").intern() will seek in the machine memory if ever someone created "aaa" string before and will return the first instance of the String ... If non has been found - the current one will be enlisted as the first and all further "aaa".intern() and new String("aaa").intern() and ("a"+"aa").intern() will return that "first" instance.

    Beware: "aaa".intern() is not very fast operation and if you will intern all strings - you will save some memory, but will loose quite a lot of CPU work.

    0 讨论(0)
提交回复
热议问题