String.equals 与 == [英] String.equals versus ==
问题描述
这段代码将一个字符串分割成tokens并存储在一个字符串数组中,然后将一个变量与第一个home进行比较......为什么它不起作用?
This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working?
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");
}
}
推荐答案
使用 string.equals(Object other)
比较字符串的函数,而不是 ==
运算符.
该函数检查字符串的实际内容,==
运算符检查对对象的引用是否相等.请注意,字符串常量通常是内嵌的",因此实际上可以将具有相同值的两个常量与 ==
进行比较,但最好不要依赖它.
The function checks the actual contents of the string, the ==
operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==
, but it's better not to rely on that.
if (usuario.equals(datos[0])) {
...
}
注意:比较是在 'usuario' 上完成的,因为这保证在您的代码中非空,尽管您仍然应该检查 datos
数组中是否确实有一些标记,否则您'会得到一个数组越界异常.
NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos
array otherwise you'll get an array-out-of-bounds exception.
这篇关于String.equals 与 ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!