srsok
srsok

Reputation: 29

Question about the mechanism of the ArrayList

Basically, when I passed arguments in Java, I knew it was passing only value.

However, the following code shows that the add method executed on SubClass's SubMethod affects ArrayList of MainClass.

MainClass.java

public class MainClass{
    public satatic void main(String[] args){
        List list = new ArrayList<>();
        SubClass subClass = new SubClass(list);
        subClass.subMethod();
        System.out.println(list) // Why added value???
    }
} 

SubClass.java

public class SubClass{
    private List list;
    public SubClass(List list){
        this.list = list;
        
    }
    public void subMethod(){
       list.add(1);
       list.add(2);
    }
} 

When I did the same thing with a HashMap's put, there was no effect on the HashMap of the MainClass.

I would like to know why only ArrayList is causing these results and what is happening inside Java.

Update

The code for the hashmap version is as follows: MainClass.java

public class MainClass{
    public satatic void main(String[] args){
        Map map = new HashMap<>();
        SubClass subClass = new SubClass(map );
        subClass.subMethod();
        System.out.println(map) // Not putting value
    }
} 

SubClass.java

public class SubClass{
    private Map map;
    public SubClass(Map map){
        this.map= map;
        
    }
    public void subMethod(){
       map = someGenerationHashMap(arg1, arg2);
    }
} 

Upvotes: 0

Views: 65

Answers (1)

Andres
Andres

Reputation: 10727

It's not about ArrayList. Any object you pass as an argument can be modified. What is passed by value is the address of the object, not the object itself.

In the Map version, you are not making any operation that could modify it. In the list version instead, you are making an add.

Make sure not to confuse objects with primitives. For example, make sure not to confuse int with Integer.

Upvotes: 2

Related Questions