这段代码将一个字符串分离为令牌,并将它们存储在一个字符串数组中,然后将一个变量与第一个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");
    }
}

当前回答

==操作符是一个简单的值比较。 对于对象引用,(值)就是(引用)。如果x和y引用同一个对象,则x == y返回true。

其他回答

使用字符串。equals(对象其他)函数用于比较字符串,而不是==操作符。

该函数检查字符串的实际内容,==操作符检查对对象的引用是否相等。请注意,字符串常量通常是“内嵌”的,这样两个具有相同值的常量实际上可以用==进行比较,但最好不要依赖于此。

if (usuario.equals(datos[0])) {
    ...
}

注意:比较是在'usuario'上完成的,因为这在你的代码中是保证非空的,尽管你仍然应该检查你实际上在datos数组中有一些令牌,否则你会得到一个数组越界异常。

==测试引用是否相等。

.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()更便宜(一个指针比较而不是一个循环),因此,在适用的情况下(例如,您可以保证您只处理实习字符串),它可以提供重要的性能改进。然而,这种情况很少见。

而不是

datos[0] == usuario

use

datos[0].equals(usuario)

==比较变量的引用,其中.equals()比较你想要的值。

a==b

比较引用,而不是值。在对象引用中使用==通常仅限于以下情况:

比较一个引用是否为空。 比较两个enum值。这是因为每个枚举常量只有一个对象。 您想知道两个引用是否指向同一个对象

“a”“b”equals()。

比较值是否相等。因为这个方法是在Object类中定义的,所有其他类都是从Object类派生出来的,所以它是为每个类自动定义的。但是,它不会对大多数类执行智能比较,除非类重写它。对于大多数Java核心类,它都以一种有意义的方式定义。如果它不是为(用户)类定义的,它的行为与==相同。

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()之间的区别

谢谢。