java的基本数据类型的包装类是引用类型吗?
本文介绍了java的基本数据类型的包装类是引用类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
public void test(Integer index){
index = new Integer(20);
}
Integer i = new Integer(30);
test(i);
System.out.println(i); //打印30
请问上面的示例中为什么打印的是30而非20?基本数据类型的包装类不是引用类型吗?
解决方案
引用JVM规范中的一段,详情参见
For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked. The new variable is initialized with the corresponding argument value from the method invocation.
规范中说每次方法调用,方法中的参数都会初始化。
上面test
方法的index
就是初始化了一个Integer
类型的变量然后指向传入的i
。后面的index = new Integer(20);
只是改变了index
变量的指向,原来i
的指向并没有改变。
这篇关于java的基本数据类型的包装类是引用类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文