且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较命令行参数参考返回false,而字符串数组返回true

更新时间:2023-02-22 12:30:16


如果我比较字符串str1 == str3的引用,则它将返回假
,因为str3是使用新字符串创建的,因此不会驻留在
字符串池中,那么str1 == strArray1 [1]如何返回true ??

if i compare reference of String str1==str3 then it will return false because str3 is created using new String so that will not reside in String pool, So how str1==strArray1[1] return true??

String strArray1 [] = new String [] { Hello, Hello}; 创建一个新的String数组,并引用相同的字符串 hello 在数组中*。

String strArray1[] = new String[] {"Hello","Hello"}; creates a new String array with a reference to the same string "hello" inside the array*.


strArray [0] == strArray [1]将返回true,strArray1 [0] == strArray1 [1]
还返回true,那么为什么命令行参数args [0] == args [1]
返回false?

strArray[0]==strArray[1] will return true, strArray1[0]==strArray1[1] also return true then why command line argument args[0]==args[1] return false?

args [0] == args [1] 返回 false ,因为它们是2个不同实例(未添加到字符串池),它们就像 new String()
您可以使用以下命令轻松测试:

args[0]==args[1] returns false, because they are 2 different instances (not added to the String pool), they are like new String(). You can easily test this using :

    System.out.println(System.identityHashCode(args[0]));
    System.out.println(System.identityHashCode(args[1]));

因此,参数传递给 main() 添加到字符串常量池

So, arguments passed to main() are NOT added to the String constants pool.