java中关于Integer 和java 中方法参数传递的几个问题
1 import java.lang.String;
2 public class Test {
3 public static void main(String[] args) {
4 int[] a = { 1, 2 };
5 // 调用swap(int,int) 典型的值传递
6 swap(a[0], a[1]);
7 System.out.println("swap(int,int):a[0]=" + a[0] + ", a[1]=" + a[1]);
8 // -----------------------------------------------------------------------------------
-----------------------------------------
9 // 引用传递,直接传递头指针的引用。改变就是改变相应地址上的值
10 swap(a, 1);
11 System.out .println("swap(int [],int):a[0]=" + a[0] + ", a[1]=" + a[1]);
12 // -----------------------------------------------------------------------------------
-----------------------------------------
13 Integer x0 = new Integer(a[0]);
14 Integer x1 = new Integer(a[1]);
15 // 调用swap(Integer,Integer)
16 swap(x0, x1);
17 System.out.println("swap(Integer,Integer):x0=" + x0 + ", x1=" + x1);
18 // -----------------------------------------------------------------------------------
-----------------------------------------
19 // intValue和valueof的区别和联系
20 // intvalue返回的是int值,而 valueof 返回的是Integer的对象,它们的调用方式也不同
21 int x = x0.intValue();
22 Integer s = Integer.valueOf(x0);
23 /*
24 * x == s输 出为true 这里面涉及到一个自动打包解包的过程,如果jdk版本过低的话没有这个功能的,所以输出的是false
25 * 现在新版本的jdk都有自动打包解包功能了
26 */
27 System.out.println("compare:int=" + x + ", Integer=" + s + " "+ (x == s));
28 // -----------------------------------------------------------------------------------
-----------------------------------------
29 StringBuffer sA = new StringBuffer("A");
30 StringBuffer sB = new StringBuffer("B");
31 System.out.println("Original:sA=" + sA + ", sB=" + sB);
32 append(sA, sB);
33 System.out.println("Afterappend:sA=" + sA + ", sB=" + sB);
34 }
35 public static void swap(int n1, int n2) {
36 int tmp = n1;
37 n1 = n2;
38 n2 = tmp;
39 }
40 public static void swap(int a[], int n) {
41 int tmp = a[0];
42 a[0] = a[1];
43 a[1] = tmp;
44 }
45 // Integer 是按引用传递的,但是Integer 类没有用于可以修改引用所指向值的方法,不像StringBuffer
46 public static void swap(Integer n1, Integer n2) { // 传递的是a 的引用,但引用本身是按值传递的
47 Integer tmp = n1;
48 n1 = n2;
49 n2 = tmp;
50 }
51 // StringBuffer和Integer一样是类,同样在方法中是引用传递,但是StringBuffer类有用于可以修改引用所指向值的方法,如.append
52 public static void append(StringBuffer n1, StringBuffer n2) {
53 n1.append(n2);
54 n2 = n1;
55 }
56 }