据我所知,Java 使用按值传递。但是如果你看下面,我传递了一个列表并向它添加了一个整数。
所需的输出:前后列表[]应该是[]
结果输出:前后列表[]是[20]
还,
如果我在静态函数中初始化列表,我想要的输出就实现了。
我能知道这种现象的原因吗
import java.util.ArrayList;
import java.util.List;
public class NormalTest {
public static void testMethod(Integer testInt, List<Integer> sampleList) {
testInt *= 2;
System.out.println(" Inside testInt :: " + testInt);
sampleList.add(testInt);
}
public static void main(String[] args) {
Integer testInt = 10;
List<Integer> sampleList = new ArrayList<>();
System.out.println(" Before testInt :: " + testInt);
System.out.println(" Before sampleList :: " + sampleList);
NormalTest.testMethod(testInt, sampleList);
System.out.println(" After testInt :: " + testInt);
System.out.println(" After sampleList :: " + sampleList);
}
}
ibeautiful
相关分类