Java:将字符串字符串与String对象进行比较 [英] Java: compare string literal with String object

查看:192
本文介绍了Java:将字符串字符串与String对象进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何比较Java中的字符串?


我已经阅读了 java.lang.String String.equals 。请考虑以下示例:

  String s1 = new String(foo); 
String s2 = new String(foo);
if(s1 == s2)... //永不发生
if(s1.equals(s2))... // OK
String s3 =bar
String s4 =bar;
if(s3 == s4)... // OK
if(s3.equls(s4))... // OK

现在关于这段代码:

  public void foo ){
if(s ==sample)...
}

如果 s 包含样本,它会按预期工作(即返回 true c $ c> string和 false 否则)? NetBeans报告此代码的警告,并建议将其替换为样本.equals(s)条件。


它是否按预期工作(即,当s包含样本
string时返回true,否则返回false)?



b $ b

这取决于,如果传递参数作为 foo(new String(Sample)) if测试将失败。如果你直接传递它像 foo(sample)如果test将返回true。

 code> foo(sample); // returns TRUE 
foo(new String(sample)); // return FALSE

public static void foo(String s){
System.out.println(s ==sample);
}

输出:

  true 
false


Possible Duplicate:
How do I compare strings in Java?

I've read about java.lang.String and String.equals. Consider the following example:

String s1 = new String("foo");
String s2 = new String("foo");
if (s1 == s2) ...      // never happens
if (s1.equals(s2)) ... // OK  
String s3 = "bar";
String s4 = "bar";
if (s3 == s4) ...     // OK
if (s3.equls(s4)) ... // OK

Now about this code:

public void foo(String s) {
    if (s == "sample") ...
}

Does it work as expected (i.e. returns true when s contains sample string and false otherwise)? NetBeans reports a warning on this code and suggests to replace it with a "sample".equals(s) condition. But I want to figure out the things behind it.

Thanks.

解决方案

Does it work as expected (i.e. returns true when s contains sample string and false otherwise)?

It depends, if you pass the argument as a foo(new String("Sample")) the if test would fail. if you pass it directly like foo("sample") if test would return true.

foo("sample"); //returns TRUE
foo(new String("sample")); //returns FALSE

public static void foo(String s) {
    System.out.println(s=="sample");
}

Output:

true
false

这篇关于Java:将字符串字符串与String对象进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆