简体   繁体   中英

Value returned from function

Suppose I've the following class:

class A{
    private Map<String, String> map;

    private Map<String, String> getMap(){
        return map;
    }

    private doActionOnMap(){
        Map<String, String> map = getMap(); //Is the map returned by getMap() 
                                            //refers to the private field map?
    }
}

That is, when some value returns by method it will be another (copy of the original) object or it will refer to the object located inside method?

这是一个参考......当你想要一个克隆时,你必须自己实现它

It is a reference type so all that you will get is a reference to the original object. It is not a copy.

I suggest you look up the difference between reference and value types

Reference Types

private Map<String, String> map;

map is a class member, it's associated with each instance of the class. If you write:

Map<String, String> myMap = a.getMap();

You'll get a reference and not a copy of it. If you change it, it'll be changed for all methods using it in this class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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