这段代码将一个字符串分离为令牌,并将它们存储在一个字符串数组中,然后将一个变量与第一个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(对象其他)函数用于比较字符串,而不是==操作符。

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

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

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


而不是

datos[0] == usuario

use

datos[0].equals(usuario)

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


你应该使用string equals来比较两个相等的字符串,而不是operator ==,它只是比较引用。


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优化的副作用。虽然它确实节省了内存资源(这就是我所说的“优化”),但它是语言的主要特征


如果在将字符串插入数组之前对其调用intern(),它也会工作。 当且仅当它们的值等于(equals())时,被连接的字符串的引用等于(==)。

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.intern();            
    i++;
}

//System.out.println (usuario);

if(datos[0]==usuario) {  
     System.out.println ("WORKING");    
}

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

谢谢。


让我们分析下面的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

==运算符比较Java中对象的引用。你可以使用字符串的equals方法。

String s = "Test";
if(s.equals("Test"))
{
    System.out.println("Equal");
}

如果你要比较字符串的任何赋值,即原始字符串,"=="和.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操作符…


使用Split而不是tokenizer,它肯定会为你提供准确的输出 如:

string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}

在此之后,我相信你会得到更好的结果.....


通常.equals用于对象比较,您想要验证两个对象是否具有相同的值。

==用于引用比较(两个对象是堆上相同的对象)&检查对象是否为空。它还用于比较基本类型的值。


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


@Melkhiah66你可以使用equals方法代替'=='方法来检查是否相等。 如果使用intern(),则检查对象是否在池中,如果存在则返回 相等否则不相等。Equals方法在内部使用hashcode并获得所需的结果。

public class Demo
{
  public static void main(String[] args)
  {
              String str1 = "Jorman 14988611";
    String str2 = new StringBuffer("Jorman").append(" 14988611").toString();
    String str3 = str2.intern();
    System.out.println("str1 == str2 " + (str1 == str2));           //gives false
    System.out.println("str1 == str3 " + (str1 == str3));           //gives true
    System.out.println("str1 equals str2 " + (str1.equals(str2)));  //gives true
    System.out.println("str1 equals str3 " + (str1.equals(str3)));  //gives true
  }
}


我知道这是一个老问题,但我是这样看的(我觉得很有用):


技术的解释

在Java中,所有变量都是基本类型或引用。

(如果你需要知道什么是引用:“对象变量”只是指向对象的指针。Object something =…,某些东西实际上是内存中的一个地址(一个数字)。

==比较准确的值。因此,它比较原始值是否相同,或者引用(地址)是否相同。这就是为什么==经常在string上不起作用;字符串是对象,对两个字符串变量执行==只是比较内存中地址是否相同,正如其他人指出的那样。equals()调用对象的比较方法,该方法将比较引用所指向的实际对象。在字符串的情况下,它比较每个字符,看它们是否相等。


有趣的是:

那么为什么==有时会为字符串返回true呢?注意字符串是不可变的。在你的代码中

String foo = "hi";
String bar = "hi";

由于字符串是不可变的(当你调用.trim()或其他东西时,它会生成一个新的字符串,而不是修改内存中指向的原始对象),所以你实际上不需要两个不同的string ("hi")对象。如果编译器是智能的,字节码将只读取生成一个String("hi")对象。所以如果你这样做

if (foo == bar) ...

之后,它们指向同一个对象,返回true。但你很少会这么想。相反,你要求用户输入,这是在内存的不同部分创建新的字符串,等等。

注意:如果你执行类似baz = new String(bar)这样的操作,编译器可能仍然会认为它们是相同的东西。但重点是,当编译器看到字面值字符串时,它可以很容易地优化相同的字符串。

我不知道它在运行时是如何工作的,但我假设JVM没有保存一个“活动字符串”列表,并检查是否存在相同的字符串。(例如,如果你读取一行输入两次,用户输入相同的输入两次,它不会检查第二个输入字符串是否与第一个输入字符串相同,并将它们指向相同的内存)。这将节省一些堆内存,但它是如此微不足道,开销是不值得的。同样,重点是编译器很容易优化文字字符串。

你知道了……对== vs. equals()以及为什么它看起来是随机的给出了一个强有力的解释。


==测试引用是否相等。

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


满足Jorman

Jorman是一个成功的商人,他有两套房子。

但其他人并不知道。

还是那个乔曼吗?

当你问麦迪逊街或伯克街的邻居时,他们唯一能说的就是:

仅从住所来看,很难确定是同一个人。因为他们是两个不同的地址,所以很自然地假设他们是两个不同的人。

这就是运算符==的行为。它会说datos[0]==usuario是假的,因为它只比较地址。

一个救援的调查员

如果我们派个调查员去呢?我们知道是同一个乔曼,但我们需要证明。我们的警探会仔细检查身体的各个方面。通过彻底的调查,代理人将能够得出结论,是否是同一个人。让我们看看它在Java术语中的情况。

下面是String的equals()方法的源代码:

它逐个字符地比较字符串,以便得出它们确实相等的结论。

这就是String =方法的行为。因此datos[0].equals(通常)将返回true,因为它执行逻辑比较。


.equals()将检查两个字符串是否具有相同的值,并返回布尔值,其中==操作符检查两个字符串是否为同一对象。


有人在更高的帖子上说==用于int和检查null。 它也可以用来检查布尔运算和字符类型。

但是要非常小心,仔细检查你使用的是char类型而不是String类型。 例如

    String strType = "a";
    char charType = 'a';

对于字符串,您将检查 这是正确的

    if(strType.equals("a")
        do something

but

    if(charType.equals('a')
        do something else

是不正确的,你需要做下面的事情

    if(charType == 'a')
         do something else

The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).

注意.equals()方法属于类Object(所有类的超类)。您需要根据您的类需求重写它,但是对于String,它已经实现,并且它检查两个字符串是否具有相同的值。

Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1;      // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2;      // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.

a==b

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

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

“a”“b”equals()。

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