这段代码将一个字符串分离为令牌,并将它们存储在一个字符串数组中,然后将一个变量与第一个home…为什么它不工作?
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");
}
}
It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.
唯一正确的方法是使用.equals() -> datos[0].equals(通常)。==表示仅当两个对象是object的相同实例(即。内存地址相同)
更新:01.04.2013我更新了这篇文章,因为下面的评论是正确的。最初我声明实习(String.intern)是JVM优化的副作用。虽然它确实节省了内存资源(这就是我所说的“优化”),但它是语言的主要特征
如果你要比较字符串的任何赋值,即原始字符串,"=="和.equals都可以,但对于新的字符串对象,你应该只使用.equals,在这里"=="将不起作用。
例子:
String a = "name";
String b = "name";
If (a == b) and (a.equals(b))将返回true。
But
String a = new String("a");
在这种情况下,if(a == b)将返回false
所以最好使用.equals操作符…