==到目前为止,我一直在我的程序中使用运算符来比较我的所有字符串.但是,我遇到了一个错误,将其中一个更改为了.equals(),并修复了该错误.
是==坏?什么时候应该不应该使用它?有什么不同?
此代码将字符串分隔为标记并将它们存储在字符串数组中,然后将变量与第一个主页进行比较...为什么它不起作用?
public static void main(String...aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos = "Jorman 14988611";
StringTokenizer tokens = new StringTokenizer(strDatos, " ");
int nDatos = tokens.countTokens();
String[] datos = new String[nDatos];
int i = 0;
while (tokens.hasMoreTokens()) {
String str = tokens.nextToken();
datos[i] = str;
i++;
}
//System.out.println (usuario);
if ((datos[0] == usuario)) {
System.out.println("WORKING");
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个不符合屏幕宽度的长字符串.例如.
String longString = "This string is very long. It does not fit the width of the screen. So you have to scroll horizontally to read the whole string. This is very inconvenient indeed.";
Run Code Online (Sandbox Code Playgroud)
为了便于阅读,我想到了这样写 -
String longString = "This string is very long." +
"It does not fit the width of the screen." +
"So you have to scroll horizontally" +
"to read the whole string." +
"This is very inconvenient indeed.";
Run Code Online (Sandbox Code Playgroud)
但是,我意识到第二种方式使用字符串连接,并将在内存中创建5个新字符串,这可能会导致性能下降.是这样的吗?或者编译器是否足够智能,以确定我需要的只是一个字符串?我怎么能避免这样做?
正如我所理解的,每当我们创建一个String文字时,都会检查池中是否存在String具有相同值的任何现有内容。如果存在,则返回对其的引用。否则会创建一个新的文字。
由此,我明白池只包含非重复的String文字。
但我对以下代码的输出感到困惑:
String str1 = "Hello World";
String str2 = "Hello";
String str3 = str2+" World";
System.out.println(str3);
System.out.println(((str1 == str3) ? "equal":"unequal"));`
Run Code Online (Sandbox Code Playgroud)
由于str3正在评估 指向"Hello World"的池中已经存在的对象,因此应该str1分配对相同对象的引用str3,因此str1并且str3应该是相等的。
但是代码显示它们是不平等的。如果有人可以解释,将不胜感激。