String s = new String(“xyz”). How many objects has been made after this line of code execute?

前端 未结 20 3045
再見小時候
再見小時候 2020-11-27 02:45

The commonly agreed answer to this interview question is that two objects are created by the code. But I don\'t think so; I wrote some code to confirm.

publi         


        
20条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 03:27

    Just because all your hash codes are the same does not mean that you are looking at the same object. Two objects are created. Let's break this down.

    String s = new String(“xyz”);
    

    In the part ' new String("xyz") ', an address is returned to the new string "xyz". When you say ' String s = ', this assigns that returned address to this object, so that they point to the same place, but the new string and string s are two seperate objects.

提交回复
热议问题