-6

重複の可能性:
Java で文字列を比較するにはどうすればよいですか?

誰かがこの状態の理由を教えてください

if (lista.getString(0)=="username")

true を返さない?私は試したことがある

if (lista.getString(0)==lista.getString(0))

うまくいかない、そして私はそれが言語の問題であることを理解しています。

4

4 に答える 4

2

==参照の等価性をテストします。

.equals値が等しいかどうかをテストします。

したがって、次を使用する必要があります。

if (lista.getString(0).equals("username"))

Java で文字列を比較するにはどうすればよいですか? を参照してください。

于 2012-06-09T16:51:37.287 に答える
1

String比較には常に を使用しますequals()

if (lista.getString(0).equals("username"))

を使用==すると、値ではなく参照を比較することになります。

さらに明確にするための簡単なスニペット:

String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2)); // true because values are same
System.out.println((s1 == s2)); // false because they are different objects
于 2012-06-09T16:51:34.323 に答える
0

Javaテクニックから

Since Strings are objects, the equals(Object) method will return true if two Strings have
the same objects. The == operator will only be true if two String references point to the  
same underlying String object. Hence two Strings representing the same content will be  
equal when tested by the equals(Object) method, but will only be equal when tested with 
the == operator if they are actually the same object.

使用する

if (lista.getString(0).equals("username"))
于 2012-06-09T16:52:49.170 に答える
0

オブジェクトを比較する正しい方法は、

object1.equals(object2)

また、String は Java のオブジェクトであるため、String についても同じことを意味します。

s1.equals(s2)

例:

if (lista.getString(0).equals("username"))
于 2012-06-09T16:57:29.743 に答える