java中关于Integer 和java 中方法参数传递的几个问题

昨晚遇到了关于方法中传递的问题,然后牵扯上了Integer,当时难以理解,后来查了一些资料,终于搞懂了。

附上方便理解的代码:

 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]); //输出为swap(int,int):a[0]=1, a[1]=2
 8 
 9  // ---------------------------------------------------
10          // 引用传递,直接传递头指针的引用。改变就是改变相应地址上的值
11          swap(a, 1);
12          System.out    .println("swap(int [],int):a[0]=" + a[0] + ",   a[1]=" + a[1]); //输出为 swap(int [],int):a[0]=2, a[1]=1
13  // ----------------------------------------------------
14          Integer x0 = new Integer(a[0]);
15          Integer x1 = new Integer(a[1]);
16          // 调用swap(Integer,Integer)
17          swap(x0, x1);
18          System.out.println("swap(Integer,Integer):x0=" + x0 + ",   x1=" + x1); //输出为 swap(Integer,Integer):x0=2, x1=1
19  // -----------------------------------------------------
20          // intValue和valueof的区别和联系
21          // intvalue返回的是int值,而 valueof 返回的是Integer的对象,它们的调用方式也不同
22          int x = x0.intValue();
23          Integer s = Integer.valueOf(x0);
24          /*
25           * x == s输 出为true 这里面涉及到一个自动打包解包的过程,如果jdk版本过低的话没有这个功能的,所以输出的是false
26           * 现在新版本的jdk都有自动打包解包功能了
27           */
28          System.out.println("compare:int=" + x + ",   Integer=" + s + "  "+ (x == s)); //输出为 compare:int=2, Integer=2 true
29  // -----------------------------------------------------
30          StringBuffer sA = new StringBuffer("A");
31          StringBuffer sB = new StringBuffer("B");
32          System.out.println("Original:sA=" + sA + ",   sB=" + sB); //输出为 Original:sA=A, sB=B
33   append(sA, sB); 33 System.out.println("Afterappend:sA=" + sA + ", sB=" + sB); //输出为 Afterappend:sA=AB, sB=B
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  }
原文地址:https://www.cnblogs.com/brock-1993/p/3501334.html