2011-09-17 16 views
0

質問1の結果についての説明を求めました。データ構造クラスでのクイズ

*** 1。次の方法の出力は?

public static void main(String[] args) { 
    Integer i1=new Integer(1); 
    Integer i2=new Integer(1); 
    String s1=new String("Today"); 
    String s2=new String("Today"); 

    System.out.println(i1==i2); 
    System.out.println(s1==s2); 
    System.out.println(s1.equals(s2)); 
    System.out.println(s1!=s2); 
    System.out.println((s1!=s2) || s1.equals(s2)); 
    System.out.println((s1==s2) && s1.equals(s2)); 
    System.out.println(! (s1.equals(s2))); 
} 

回答:

false 
false 
true 
true 
true 
false 
false 

+1

*あなたはどう思いますか?私たちがそれを知っていれば、私たちはあなたをもっと良く助けることができます。 –

答えて

5
Integer i1=new Integer(1); 
Integer i2=new Integer(1); 
String s1=new String("Today"); 
String s2=new String("Today"); 

// do i1 and 12 point at the same location in memory? No - they used "new" 
System.out.println(i1==i2); 

// do s1 and s2 point at the same location in memory? No - the used "new" 
System.out.println(s1==s2); 

// do s1 and s2 contain the same sequence of characters ("Today")? Yes. 
System.out.println(s1.equals(s2)); 

// do s1 and s2 point at different locations in memory? Yes - they used "new" 
System.out.println(s1!=s2); 

// do s1 and s2 point to different locations in memory? Yes - they used "new". 
// Do not check s1.equals(s2) because the first part of the || was true. 
System.out.println((s1!=s2) || s1.equals(s2)); 

// do s1 and s2 point at the same location in memory? No - they used "new". 
// do not check s1.equals(s2) because the first part of the && was false. 
System.out.println((s1==s2) && s1.equals(s2)); 

// do s1 and s2 not contain the same sequence of characters ("Today")? No. 
System.out.println(! (s1.equals(s2))); 
5

私は、主なポイントは、equalsが値を比較し、一方==が、彼らは同じインスタンスを参照するかどうかを確認するために2つのオブジェクト参照を比較していることだと思います。

たとえば、s1とs2は2つの異なる文字列インスタンスなので、==はfalseを返しますが、両方とも値"Today"を含むため、equalsがtrueを返します。

0

どの結果が特にありますか? thisは役に立ちますか?

1

IntegerStringがオブジェクトであることに留意して、==演算子は実際のオブジェクト自体ではなく、2つのポインタのメモリアドレスを比較します。したがって、最初の2 ==は、i1i2と同じオブジェクトではないため、falseになります。初期化が次の場合:

Integer i1=new Integer(1); 
Integer i2=i1; 

最初のprintln()はtrueです。

s1.equals(s2)は、オブジェクトの等価性を比較する適切な方法です。 String.equals()メソッドは文字列の等価性をチェックするので、 "Today"と "Today"は等しい文字列です。 S1、S2は非常に簡単ブール演算でなければなりません==

残りの部分とI1とI2の問題に似て異なるオブジェクトですので、

s1!=s2はtrueです。