简体   繁体   English

关于ArrayList的机制问题

[英]Question about the mechanism of the ArrayList

Basically, when I passed arguments in Java, I knew it was passing only value.基本上,当我在 Java 中通过 arguments 时,我知道它只传递了值。

However, the following code shows that the add method executed on SubClass 's SubMethod affects ArrayList of MainClass .但是,以下代码显示在SubClassSubMethod上执行的 add 方法会影响ArrayListMainClass

MainClass.java 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子类.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 .当我对HashMapput做同样的事情时,对HashMapMainClass没有影响。

I would like to know why only ArrayList is causing these results and what is happening inside Java.我想知道为什么只有ArrayList会导致这些结果,以及 Java 内部发生了什么。

Update更新

The code for the hashmap version is as follows: MainClass.java hashmap版本代码如下: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子类.java

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

It's not about ArrayList.这与 ArrayList 无关。 Any object you pass as an argument can be modified.您作为参数传递的任何 object 都可以修改。 What is passed by value is the address of the object, not the object itself.传值的是object的地址,而不是object本身。

In the Map version, you are not making any operation that could modify it.在 Map 版本中,您没有进行任何可以修改它的操作。 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 .例如,确保不要将intInteger混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM