2016-09-26 3 views
-2
public class MainClass 
{ 
    private String name=""; 

    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
    public static void main(String[] args) 
    { 
     ArrayList<String> al=new ArrayList<String>(); 
     String str=new String("abc"); 
     al.add(str); 
     str="def"; 
     al.add(str); 
     str="ghi"; 
     al.add(str); 
     str="jkl"; 
     al.add(str); 
     System.out.println(al); 

     ArrayList<MainClass> al1=new ArrayList<MainClass>(); 
     MainClass mainclass=new MainClass(); 
     mainclass.setName("Abhi"); 
     al1.add(mainclass); 
     mainclass.setName("Sajith"); 
     al1.add(mainclass); 
     mainclass.setName("Sridhar"); 
     al1.add(mainclass); 

     for(MainClass main:al1) 
      System.out.println(main.getName()); 
    } 
} 

出力:このコードのオブジェクトはどのように機能しますか?

[abc, def, ghi, jkl] 
Sridhar 
Sridhar 
Sridhar 

なぜそれが最初のケースで起こっていないときに、私のオブジェクトが第二の場合にオーバーライドを得ていますか?

+5

新しいMainClass();オブジェクトを作成するのは1つだけなので、3つの異なる値を設定すると、この1つのオブジェクトが設定されることを期待する必要があります。デバッガのコードをステップ実行して、何が起こっているのかを正確に把握できるはずです。 –

+0

'new String'を使うのか、文字列リテラルを使うのかにかかわらず、4つの異なる文字列があります。 –

+0

ArrayList al = new ArrayList (); ArrayListと同じです。 al = new ArrayList <>();と悪い練習String String str = new String( "abc"); String str = "abc";を実行します。 – Tokazio

答えて

1
ArrayList<String> al=new ArrayList<String>(); 
    //a1 is empty ArrayList of Strings. 
    String str=new String("abc"); 
    //str is now a reference to "abc" 
    al.add(str); 
    //a1 has now reference to "abc" 
    str="def"; 
    //str has now reference to "def" 
    al.add(str); 
    //a1 has now reference to "abc" and reference to "def" 
    str="ghi"; 
    //str has now reference to "ghi" 
    al.add(str); 
    //a1 has now three different references 
    str="jkl"; 
    //str has now reference to "jkl" 
    al.add(str); 
    //a1 has now four different references. 
    System.out.println(al); 

    ArrayList<MainClass> al1=new ArrayList<MainClass>(); 
    //al1 is now empty 
    MainClass mainclass=new MainClass(); 
    //mainclass has now reference to an object with an empty String 
    mainclass.setName("Abhi"); 
    //mainclass' reference didn't change. It's still the same, however the string is different 
    al1.add(mainclass); 
    //al1 has now one reference to the mainclass 
    mainclass.setName("Sajith"); 
    //mainclass' reference didn't change. It's still the same, however the string is different 
    al1.add(mainclass); 
    //al1 has now two references to the mainclass 
    mainclass.setName("Sridhar"); 
    //mainclass' reference didn't change. It's still the same, however the string is different 
    al1.add(mainclass); 
    //al1 has now three references to the mainclass 

    for(MainClass main:al1) 
     System.out.println(main.getName()); 

したがって、最初のArrayListには異なる値を指す4つの異なる参照があります。 2番目のArrayListにはmainClassという同じ参照が3回あり、末尾に "Sridhar"というStringを表します。

関連する問題