这段代码将一个字符串分离为令牌,并将它们存储在一个字符串数组中,然后将一个变量与第一个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");
}
}
满足Jorman
Jorman是一个成功的商人,他有两套房子。
但其他人并不知道。
还是那个乔曼吗?
当你问麦迪逊街或伯克街的邻居时,他们唯一能说的就是:
仅从住所来看,很难确定是同一个人。因为他们是两个不同的地址,所以很自然地假设他们是两个不同的人。
这就是运算符==的行为。它会说datos[0]==usuario是假的,因为它只比较地址。
一个救援的调查员
如果我们派个调查员去呢?我们知道是同一个乔曼,但我们需要证明。我们的警探会仔细检查身体的各个方面。通过彻底的调查,代理人将能够得出结论,是否是同一个人。让我们看看它在Java术语中的情况。
下面是String的equals()方法的源代码:
它逐个字符地比较字符串,以便得出它们确实相等的结论。
这就是String =方法的行为。因此datos[0].equals(通常)将返回true,因为它执行逻辑比较。
让我们分析下面的Java,来理解string的恒等式:
public static void testEquality(){
String str1 = "Hello world.";
String str2 = "Hello world.";
if (str1 == str2)
System.out.print("str1 == str2\n");
else
System.out.print("str1 != str2\n");
if(str1.equals(str2))
System.out.print("str1 equals to str2\n");
else
System.out.print("str1 doesn't equal to str2\n");
String str3 = new String("Hello world.");
String str4 = new String("Hello world.");
if (str3 == str4)
System.out.print("str3 == str4\n");
else
System.out.print("str3 != str4\n");
if(str3.equals(str4))
System.out.print("str3 equals to str4\n");
else
System.out.print("str3 doesn't equal to str4\n");
}
当第一行代码String str1 = "Hello world."执行时,一个字符串\Hello world."
创建,变量str1引用它。由于优化,下一行代码执行时不会再次创建另一个字符串“Hello world.”。变量str2也引用现有的“Hello world.”。
运算符==检查两个对象的同一性(两个变量是否引用同一个对象)。由于str1和str2在内存中引用同一个字符串,所以它们彼此是相同的。equals方法检查两个对象是否相等(两个对象是否具有相同的内容)。当然,str1和str2的内容是相同的。
当代码String str3 = new String("Hello world.")执行时,将创建一个内容为"Hello world."的String的新实例,该实例由变量str3引用。然后再次创建内容为"Hello world."的string的另一个实例,并由
str4。因为str3和str4引用了两个不同的实例,所以它们并不相同,但它们是相同的
内容相同。
因此,输出包含四行:
Str1 == str2
Str1 equals str2
Str3! = str4
Str3 equals str4
如果你要比较字符串的任何赋值,即原始字符串,"=="和.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操作符…