package com.jstyle.demo;
import java.util.ArrayList;
import java.util.List;
public class ParaPassingTest {
public void test1() {
int[] x = new int[2];
x[0] = 1;
x[1] = 2;
test2(x);
System.out.println("x[0]=" + x[0]);
System.out.println("x[1]=" + x[1]);
int[] xx = new int[2];
xx[0] = 1;
xx[1] = 2;
test3(xx);
System.out.println("xx[0]=" + xx[0]);
System.out.println("xx[1]=" + xx[1]);
int y = 12;
test4(y);
System.out.println("y=" + y);
String str = new String("hello");
List<String> list = new ArrayList<String>();
list.add("hello");
test5(str, list);
System.out.println("str=" + str);
System.out.println("list.get(0)= " + list.get(0));
Integer i = new Integer(5);
Double d = new Double(78);
Float f = new Float(45.36);
Character c = new Character('c');
test6(i, d, f, c);
System.out.println("i=" + i);
System.out.println("d=" + d);
System.out.println("f=" + f);
System.out.println("c=" + c);
}
public void test2(int[] x) {
x = new int[2];
x[0] = 5;
x[1] = 6;
}
public void test3(int[] x) {
x[0] = 5;
x[1] = 6;
}
public void test4(int y) {
y = y + 10;
}
public void test5(String str, List<String> list) {
str = "world";
list.set(0, "world");
}
public void test6(Integer i, Double d, Float f, Character c) {
i = 6;
d = 789D;
f = 45.363f;
c = 'd';
}
public static void main(String[] args) {
ParaPassingTest test = new ParaPassingTest();
test.test1();
}
}
前几天遇到一个问题,一个方法中传入了String型的变量str,在方法内修改str的值,但是方法没有返回这个str,而是在调用后直接使用这个str。本以为str的值应该改变,但是实际上没有。可参照以上代码。
在Java中,对象的传递,String和包装类除外,是按址传递。
String和包装类以及基本数据类型,是按值传递。包装类的特质之一是对其值进行操作时会体现出其对应的基本类型的性质。String的存储实际上通过char[]来实现,相当于是char[]的包装类。