Start New Discussion within our Software Development Community

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. 

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

This question has already been answered. Start a new discussion instead.