简介
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
System.out.printf("a = %s, b = %s\n", a, b);
swap(a, b);
System.out.printf("a = %s, b = %s\n", a, b);
}
public static void swap(Integer a, Integer b) {
// TODO 实现
}
// 特别提醒,这是错误的方式
// 特别提醒,这是错误的方式
// 特别提醒,这是错误的方式
public static void swap(Integer a, Integer b) {
// TODO 实现
Integer temp = a;
a = b;
b = temp;
}
形参和实参
参数值传递
自动装箱
形参和实参
public void test() {
int shi_can = ;
testA(shi_can);
}
public void testA(int xing_can) {
}
注:为了清楚的表达意思,我命名的时候并没有按照java的驼峰规则命名,这里只是为了演示
值传递和引用传递
值传递:传递的是实际值,像基本数据类型
引用传递:将对象的引用作为实参进行传递
// 仅仅是一个java对象
public class IntType {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
// main方法
public class Int*wap {
public static void main(String[] args) {
// CODE_1
IntType type1 = new IntType();
type1.setValue(1);
IntType type2 = new IntType();
type2.setValue(2);
// CODE_1
swap1(type1, type2);
System.out.printf("type1.value = %s, type2.value = %s", type1.getValue(), type2.getValue());
swap2(type1, type2);
System.out.println();
System.out.printf("type1.value = %s, type2.value = %s", type1.getValue(), type2.getValue());
}
public static void swap2(IntType type1, IntType type2) {
int temp = type1.getValue();
type1.setValue(type2.getValue());
type2.setValue(temp);
}
public static void swap1(IntType type1, IntType type2) {
IntType type = type1;
type1 = type2;
type2 = type;
}
}
…
…
type1.value = 1, type2.value = 2
type1.value = 2, type2.value = 1
public static void swap1(IntType type1, IntType type2) {
IntType type = type1;
type1 = type2;
type2 = type;
}
自动装箱
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
System.out.printf("a = %s, b = %s\n", a, b);
swap(a, b);
System.out.printf("a = %s, b = %s\n", a, b);
}
public static void swap(Integer a, Integer b) {
Integer temp = a;
a = b;
b = temp;
}
回归
public static void swap(Integer a, Integer b) {
// TODO 实现
// 无解,
}
private final int value;
...
public Integer(int value) {
this.value = value;
}
public static void swap(Integer a, Integer b) {
int temp = a.intValue();
try {
Field value = Integer.class.getDeclaredField("value");
value.setAccessible(true);
value.set(a, b);
value.set(b, temp);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
a = 1, b = 2
a = 2, b = 2
public static void swap(Integer a, Integer b) {
int temp = a.intValue();
try {
Field value = Integer.class.getDeclaredField("value");
value.setAccessible(true);
value.set(a, b);
value.set(b, new Integer(temp));
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}