0

Hi,

    I have code like this,

      public void method1(){
            ArrayList<String> list=new ArrayList<String>();
            list.add("A");
            list.add("C");
            list.add("D");
           for(int i=0;i<list.size();i++){

               if(i==0){
                  new Test().addB(list);
                 }
           }
           System.out.println(list)
         }  
           public void addB(ArrayList<String> list1)
               {
                list1.add(1,"B");
                System.out.println(list1);
                }

output: 
         List1: A,B,C,D
         List : A,B,C,D

I Expected this Result: 
         List1: A,B,C,D
         List : A,C,D

Why List1 is overridding to list?  Kindly share about this. 

Edited by pritaeas: Moved to Java.

2
Contributors
1
Reply
12
Views
3 Years
Discussion Span
Last Post by JamesCherrill
1

Onl line 4 you create an ArrayList, and a reference variable that refers to it.
On line 11 you call addB passing the reference (the variable called list) to your ArrayList.
In that method you get a copy of that reference and you call that list1.

Now list and list1 contain the same value, ie a reference to your ArrayList. It doesn't matter whether you use list or list1, they both refer too exactly the same ArrayList

Edited by JamesCherrill

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.