这段代码将一个字符串分离为令牌,并将它们存储在一个字符串数组中,然后将一个变量与第一个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");
}
}
==测试引用是否相等。
.equals()测试值是否相等。
因此,如果你真的想测试两个字符串是否具有相同的值,你应该使用.equals()(除非在少数情况下,你可以保证具有相同值的两个字符串将由相同的对象表示,例如:字符串实习)。
==用于测试两个字符串是否是同一个Object。
// These two have the same value
new String("test").equals("test") ==> true
// ... but they are not the same object
new String("test") == "test" ==> false
// ... neither are these
new String("test") == new String("test") ==> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" ==> true
// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st" ==> true
// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false
值得注意的是,==比equals()更便宜(一个指针比较而不是一个循环),因此,在适用的情况下(例如,您可以保证您只处理实习字符串),它可以提供重要的性能改进。然而,这种情况很少见。
equals()函数是Object类的一个方法,程序员需要重写它。String类重写它,以检查两个字符串是否相等,即在内容和不引用。
==运算符检查两个对象的引用是否相同。
考虑程序
String abc = "Awesome" ;
String xyz = abc;
if(abc == xyz)
System.out.println("Refers to same string");
这里的abc和xyz,都是指同一个字符串“Awesome”。因此表达式(abc == xyz)为真。
String abc = "Hello World";
String xyz = "Hello World";
if(abc == xyz)
System.out.println("Refers to same string");
else
System.out.println("Refers to different strings");
if(abc.equals(xyz))
System.out.prinln("Contents of both strings are same");
else
System.out.prinln("Contents of strings are different");
这里abc和xyz是两个具有相同内容“Hello World”的不同字符串。因此,表达式(abc == xyz)为假,而as (abc.equals(xyz))为真。
希望你理解==和<Object>.equals()之间的区别
谢谢。