Redian新闻
>
在一个函数里把arraylist设为null 但是有问题
avatar
在一个函数里把arraylist设为null 但是有问题# Java - 爪哇娇娃
s*y
1
下面这个例子里面 makenull函数传入一个ArrayList的instance, 在函数里把它
设为null, 但是函数返回后, main函数里的这个instance并不为null.
这是为什么阿?
public class test {
public static void makenull(java.util.ArrayList s){
s = null;
}
public static void main(String[] args) {
java.util.ArrayList s = new java.util.ArrayList();
test.makenull(s);
// after test.makenull function, s is NOT null
}
}
avatar
o*v
2
passed by value, always. 【 在 starrysky (冰糖葫芦_爱可不可以永远幸福没有悲伤) 的大作中提到: 】
avatar
xt
3

伤) 的大作中提到: 】
别和通常意义上的pass by value混淆.其实pass by reference就是建立在pass by
value上的,
区别是pass by reference被pass 的是reference(pointer)的value而不是instance
value.
因此Java可以认为是pass by value,因为object在程序中是以reference来表示的.因此在
传递
reference的时候实际上是pass by value.
上面那段和下面的没有区别:
int n=10;
makeZero(n);
...
void makeZero( int n ) { n=0;}
caller方的n是不会变的,因为被改变的是n的一个copy.

【在 o**v 的大作中提到】
: passed by value, always. 【 在 starrysky (冰糖葫芦_爱可不可以永远幸福没有悲伤) 的大作中提到: 】
avatar
s*y
4
thanks a lot
但是你们的解释还是没法说服我
我看到下面这样的解释 觉得比较明白叻
public class MyApp {
public static void makenull(java.util.ArrayList c) {
// c - is a new refference on object of ArrayList class
// value of c refference is same as in s
// so you have two reffeneces on same object
c=null; // here you make c (one of this refference) as null
}
public static void main(String[] args) {
java.util.ArrayList s = new java.util.ArrayList();
MyApp.makenull(s);
//s - is still reffere

【在 xt 的大作中提到】
:
: 伤) 的大作中提到: 】
: 别和通常意义上的pass by value混淆.其实pass by reference就是建立在pass by
: value上的,
: 区别是pass by reference被pass 的是reference(pointer)的value而不是instance
: value.
: 因此Java可以认为是pass by value,因为object在程序中是以reference来表示的.因此在
: 传递
: reference的时候实际上是pass by value.
: 上面那段和下面的没有区别:

avatar
o*v
5
值传递呀,永远是【 在 starrysky (冰糖葫芦_爱可不可以永远幸福没有悲伤) 的大作中提到: 】
avatar
r*l
6
You can not make the ArrayList null in this example. While if you want to
just clear the ArrayList, this works:
public static void makeEmpty(java.util.ArrayList s) {
s.clear();
}
BTW: makenull is not a good name, make it makeNull, using the java
convention.

【在 s*******y 的大作中提到】
: 下面这个例子里面 makenull函数传入一个ArrayList的instance, 在函数里把它
: 设为null, 但是函数返回后, main函数里的这个instance并不为null.
: 这是为什么阿?
: public class test {
: public static void makenull(java.util.ArrayList s){
: s = null;
: }
: public static void main(String[] args) {
: java.util.ArrayList s = new java.util.ArrayList();
: test.makenull(s);

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。