java双等号比较字符串,Java与两个字符串==比较是错误的?

==运算符比较对象引用,而不是String的值。

要比较String的值,请使用String.equals方法:

"231".equals(parts[0]);

Java中的任何其他对象都是如此 – 比较值时,始终使用equals方法而不是使用==运算符。

equals方法是Object一部分,并且应该被以某种方式进行比较的类重写。

如果字符串没有被拦截,那么==检查引用标识。 使用:

"231".equals(parts[0]);

代替。

Java中的==比较对象的地址(在这种情况下是字符串)。

你想要的是parts[0].equals("231")

以下打印出“true”;

String s = "231"; if(s == "231") { System.out.println("true"); } else { System.out.println("false"); }

这是因为字符串不可变,java会尽可能的节省空间,所以它指向相同的内存引用。

但是,下面打印出“false”:

String s = new String("231"); if(s == "231") { System.out.println("true"); } else { System.out.println("false"); }

new会迫使它将字符串存储在新的内存位置。

顺便说一句,你应该总是使用.equals()来比较字符串(就像这个例子)

使用equals方法:parts [0] .equals(“231”)。 ==运算符比较对象引用。

“==”比较对象引用,在你的情况下,“231”与part [0]是不同的对象。

你想使用String.equals 。

parts[0].equals("231")

答案很简单:当通过==运算符比较字符串时,实际上比较两个不同的变量是否引用一个String对象。 而他们不这样做,数组中的字符串和新创建的“231”是不同的具有相同内容的String对象。

正确的做法是使用下列表达式: "231".equals(parts[0])或"231".equalsIgnoreCase(parts[0]) 。 这将给你你所需要的,如果这些String对象包含相同的值,则返回true。

我认为在测试用例中表达答案可能会有所帮助:

public class String231Test extends TestCase { private String a; private String b; protected void setUp() throws Exception { a = "231"; StringBuffer sb = new StringBuffer(); sb.append("231"); b = sb.toString(); } public void testEquals() throws Exception { assertTrue(a.equals(b)); } public void testIdentity() throws Exception { assertFalse(a == b); } }

你也可以使用compareTo(String)方法:

String str = "test"; if( str.compareTo("test") == 0) //the argument string is equal to str; else //the argument string is not equal to str;

使用equals方法来比较对象:

String[] test = {"231", "CA-California", "Sacramento-155328", "aleee", "Customer Service Clerk", "Alegra Keith.doc.txt"}; System.out.println("231".equals(test[0]));

比较'=='比较引用,而不是值。

这是一个非常好的例子。 在Java中,使用字符串的'=='运算符可能非常棘手。

class Foo { public static void main(String[] args) { String a = "hello"; String b = "hello"; String c = "h"; c = c + "ello"; String operator = null; if(a == b) { operator = " == "; } else { operator = " != "; } System.out.println(a + operator + b); if(a == c) { operator = " == "; } else { operator = " != "; } System.out.println(a + operator + c); if(a == "hello") { operator = " == "; } else { operator = " != "; } System.out.println(a + operator + "hello"); if(c == "hello") { operator = " == "; } else { operator = " != "; } System.out.println(c + operator + "hello"); } }

这将产生以下输出:

hello == hello hello != hello hello == hello hello != hello

正如许多其他人已经解释过的那样,您尝试与等号运算符进行比较,但是它将依赖于Object.equals()而不是String.equals()。

所以你可以通过显式调用String.equals()来完成这个工作,而不是写作

parts[0].equals("blahblah")

我更喜欢这样的:

"blahblah".equals(parts[0])

因为它避免了测试零件[0]潜在的无效性(但要小心零件变量本身可能是空的…)

另一种方法是使用String.intern():

if (parts[0].intern() == "blahblah") ...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值