通过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);
}
}
# 1 楼答案
您正在将引用的副本传递给对象实例
如果你直接改变对象。e、 g.
col.add
它将更改基础对象如果更改它所引用的对象。例如
new Integer()
它只会更改局部变量的引用# 2 楼答案
不一样
更改引用
entero
,而更改引用的对象
col
# 3 楼答案
简而言之:原语类型和“原语包装器(整数、长、短、双精度、浮点、字符、字节、布尔)”不能通过引用进行更改
查看http://en.wikipedia.org/wiki/Immutable_object了解详细信息
# 4 楼答案
{ 此处创建的对象将在大括号(})结束后销毁
}