何时HashMap.values()/ HashMap.keySet()按引用返回以及何时返回值?

时间:2013-08-01 00:30:16

标签: 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()。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

简而言之,java对象具有一些非常特殊的属性。

通常,java具有直接按值传递的基本类型(int,bool,char,double等)。然后java有对象(从java.lang.Object派生的所有东西)。实际上,对象总是通过引用来处理(引用是一个你无法触摸的指针)。这意味着实际上,对象是按值传递的,因为引用通常不是很有趣。但它确实意味着您无法更改指向哪个对象,因为引用本身是按值传递的。

要简化您的问题,请参阅以下代码

@Test
public void testIntegerValue() {
    Integer num = new Integer(1);
    setInteger(num);
    System.out.println(num); // still return one, why? because Integer will convert to 
                            // int internally and int is primitive in Java, so it's pass by value

}

public void setInteger(Integer i) {
    i +=1;
}