集合中存储的是对象的值还是对象的引用

如果是基本数据类型(基本数据类型对象),集合(List / LinkList / Map)存的是值,

如果存的是对象,则集合存的是对象的引用,如下代码:

import java.util.*;

public class Main {

    public static void main(String[] args) {
        List list1 = new ArrayList();
        List linkList1 = new LinkedList();
        Map map1 = new HashMap();
        Integer i = 1;
        list1.add(i);
        linkList1.add(i);
        map1.put("i",i);
        i = 2;

        System.out.println(list1.get(0));
        System.out.println(linkList1.get(0));
        System.out.println(map1.get("i"));
        System.out.println("===================");

        List list2 = new ArrayList();
        List linkList2 = new LinkedList();
        Map map2 = new HashMap();
        Man man = new Man();
        man.setName("zhangsan");
        man.setAge("25");

        list2.add(man);
        linkList2.add(man);
        map2.put("man", man);

        man.setName("lisi");

        Man b1 = (Man) list2.get(0);
        Man b2 = (Man) linkList2.get(0);
        Man b3 = (Man) map2.get("man");
        System.out.println(b1.getName());
        System.out.println(b2.getName());
        System.out.println(b3.getName());
    }
}

class Man{
    protected String name;
    protected String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

result:

1
1
1
===================
lisi
lisi
lisi

 

你可能感兴趣的:(Java基础,面试题)