0

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

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=假

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

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()。

4

2 回答 2

3

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

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

于 2013-08-01T01:11:54.650 回答
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;
}
于 2013-08-01T00:51:38.493 回答