java - HashMap.values()/HashMap.keySet()什么时候按引用返回,什么时候按值返回?

标签 java reference hashmap

下面的代码表明值是通过引用返回的:

public class Playground {

    public static void main(String[] args) {
        Map<Integer, vinfo> map = new HashMap<Integer, vinfo>(); 
        map.put(1, new vinfo(true));
        map.put(2, new vinfo(true));
        map.put(3, new vinfo(true));


        for(vinfo v : map.values()){
            v.state = false;
        }

        printMap(map);
    }

    public static void printMap(Map m){
        Iterator it = m.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry pairs = (Map.Entry) it.next();
            Integer n = (Integer) pairs.getKey();
            vinfo v = (vinfo) pairs.getValue();
            System.out.println(n + "=" + v.state);
        }
    }
}

class vinfo{
    boolean state;

    public vinfo(boolean state){
        this.state = state;
    }
}

输出:
1=假
2=假
3=假

在下面的代码中,它们是按值返回的。然而;我正在使用 Integer 对象。

public class Playground {

    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
        map.put(1, 1);
        map.put(2, 1);
        map.put(3, 1);


        for(Integer n : map.values()){
            n+=1;
        }

        printMap(map);
    }

    public static void printMap(Map m){
        Iterator it = m.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry pairs = (Map.Entry) it.next();
            Integer n = (Integer) pairs.getKey();
            Integer n2 = (Integer) pairs.getValue();
            System.out.println(n + "=" + n2);
        }
    }
}

输出:
1=1
2=1
3=1

我如何知道何时直接更改值(或与此相关的键)或者我必须执行完整的 .remove() 和 .put()。

最佳答案

整数是不可变的。一旦构造了 Integer 的特定实例,就无法更改该实例的值。但是,您可以将 Integer 变量设置为等于 Integer 的不同实例(除非该变量被声明为 Final)。您的赋值 (+=) 正在构造一个新的 Integer 对象并设置变量 n 来引用它。

您的类 vinfo 不是一成不变的,因此其行为符合您的预期。

关于java - HashMap.values()/HashMap.keySet()什么时候按引用返回,什么时候按值返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17983306/

相关文章:

Java代理连接到postgres

java - 在 Java Spring 中将 JSON 绑定(bind)到 Arraylist?

java - Drools 规则取决于来自 JDK Map 的知识(不在非 JDK 类中)

reference - 尝试转移所有权时无法移出借用的内容

C映射数据结构

JAVA - 使用字符串创建HashMap

java - WebSocket ConvertAndSendToUser 无法接收消息

java - 单元 : How to write test case using jUnit and Mockito

c++ - 我们可以说没有别名,指针和引用是完全一样的东西吗

rust - 从rust中的函数返回引用值