有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过Ref传递Java。整数未修改,集合已修改,为什么?

我有两个例子不明白

Java将值作为变量传递或通过引用传递

为什么在Ref类中整型变量没有更改(null)? 为什么在RefCol类中集合变量被修改col(1)

类别参考:

test(): entero: 5

inicio(): entero: null

类RefCol:

test(): col: [1]

inicio(): col: [1] 

import java.util.Collection;
import java.util.Vector;


public class Ref {

    public static void main(String[] args){
        Ref ref = new Ref();
        ref.inicio();
    }

    public void inicio(){
        Integer entero = null;
        test(entero);
        System.out.println("inicio(): entero: " + entero);
    }

    public void test(Integer entero){
        entero = new Integer(5);
        System.out.println("test(): entero: " + entero);
    }

}





public class RefCol {

    public static void main(String[] args){
        RefCol ref = new RefCol();
        ref.inicio();
    }

    public void inicio(){
        Collection col = new Vector();
        test(col);
        System.out.println("inicio(): col: " + col);
    }

    public void test(Collection col){
        col.add( new Integer(1) );
        System.out.println("test(): col: " + col);
    }

}

共 (4) 个答案

  1. # 1 楼答案

    您正在将引用的副本传递给对象实例

    如果你直接改变对象。e、 g.col.add它将更改基础对象

    如果更改它所引用的对象。例如new Integer()它只会更改局部变量的引用

  2. # 2 楼答案

    不一样

    entero = new Integer(5);
    

    更改引用entero,而

    col.add(new Integer(1));
    

    更改引用的对象col

  3. # 3 楼答案

    简而言之:原语类型和“原语包装器(整数、长、短、双精度、浮点、字符、字节、布尔)”不能通过引用进行更改

    查看http://en.wikipedia.org/wiki/Immutable_object了解详细信息

  4. # 4 楼答案

    { 此处创建的对象将在大括号(})结束后销毁

    }