为什么我们不应该使用==来比较字符串? [英] Why we shouldn't use == to compare strings?

查看:176
本文介绍了为什么我们不应该使用==来比较字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用显式或隐式结构创建字符串。

We can create Strings using explicit or implicit constructions.

隐式构造示例:

String str1 = "hello";
String str2 = "hello";
str1==str2 // returns true, both str1 and str2 points to the same String object in string pool

显式构造示例

String str3 = new String("hello");
String str4 = new String("hello")
str3==str4 // returns false because str3 and str4 points to different String object

由于首选(内存保存)使用隐式构造,为什么我们不应该使用==运算符?据我所知,不使用==运算符的唯一原因是我们可以忘记不使用显式结构并尝试做类似

Since it's preferred (memory save) to use implicit construction why we shouldn't use == operator? As far as I know the only one reason to not use == operator is that we can forget about not using explicit constructions and try to do something like

str1==str3
str3==str4 // and so forth


推荐答案

Literal来自您的代码的字符串被实习。这就是为什么它们在你的例子中是同一个对象。

Literal strings, coming from your code, are interned. That's why they're the same object in your example.

但是你的程序中并非所有字符串都来自你的代码,有些来自各种输入(例如用户输入)或者从文件)或者你构建它们的操作,以及那些字符串没有实现(除非你要求它)。这些字符串通常不是 == ,即使它们等于

But not all strings in your program come from your code, some come from various inputs (for example a user input, or a file) or from operations you do to build them, and those strings aren't interned (unless you ask for it). Those strings aren't usually == even when they're equal.

这篇关于为什么我们不应该使用==来比较字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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