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

前端 未结 20 2981
再見小時候
再見小時候 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:16

    java.lang.String overrides the hashCode() method so that the value depends on the content of the string.

    As a result, hashCode() does not tell you anything about the number of instances. It may be the same string or may be another instance with no single byte shared. Same about equals(). This explains your output.

    Use System.identityHashCode(..) for this kind of research.

    And may the source be with you.

提交回复
热议问题