对于对象,Java是否通过值传递?

时间:2014-03-10 06:37:37

标签: java

我搜索了很多,每一个发现java都是通过值传递的,但我仍然不满意答案。 下面是代码。在这里,如果我传递HashMap的对象,那么我得到它的更新值,而在整数的情况下,它不是那样的。这两者有什么区别。 在这两种情况下,如何通过价值传递 -

public static void main(String[] args) {
    HashMap hm = new HashMap();
    System.out.println(hm.size()); //Print 0

    operation(hm);
    System.out.println(hm.size()); //Print 1 ; Why it's updating the HashMap.

    Integer c = new Integer(3);
    System.out.println(c); //Print 3

    getVal(c);
    System.out.println(c); //Print 3: Why it's not updating the integer like HashMap.
}

public static void operation(HashMap h) {
    h.put(“key”, “java”);
}

public static void getVal(Integer x) {
    x = x + 2;
    System.out.println(x);
}

3 个答案:

答案 0 :(得分:2)

  

这里,如果我传递hashmap的对象

你不是。您正在传递对hashmap的引用。引用按值传递。

答案 1 :(得分:1)

在java-中“对象的引用按值传递”。

流程:

public static void main(String[] args) {
    HashMap hm = new HashMap();
    System.out.println(hm.size()); //Print 0 

    operation(hm);
    System.out.println(hm.size()); //Print 1 ; Why it's updating the HashMap.

    Integer c = new Integer(3);
    System.out.println(c); //Print 3

    getVal(c);
    System.out.println(c); //Print 3: Why it's not updating the integer like HashMap.
}

public static void operation(HashMap h) {  --> You are modifying the object pointed by hm. now both references hm and h  point to the same HashMap
    h.put(“key”, “java”);
}

public static void getVal(Integer x) {  // here X and c both point to same Integer object.
    x = x + 2;   // Now X and c point to different Integer objects. and X will not be visible outside this method. So the value of c will not change.               
    System.out.println(x);
}

答案 2 :(得分:0)

对于引用类型参数,引用按值传递,这意味着您无法修改引用本身(例如,您不能将其设置为null)。

您仍然可以修改引用指向的对象(例如,修改其属性)。