如何在 Java 中交換或互換物件?


Java 使用按值呼叫將引數傳遞給函式。要交換物件,我們需要使用它們的包裝器。請看下面的示例: -

示例

 動態演示

public class Tester{
   public static void main(String[] args) {
      A a = new A();
      A b = new A();

      a.value = 1;
      b.value = 2;

      //swap using objects
      swap(a,b);
      System.out.println(a.value +", " + b.value);

      Wrapper wA = new Wrapper(a);
      Wrapper wB = new Wrapper(b);

      //swap using wrapper of objects
      swap(wA,wB);
      System.out.println(wA.a.value +", " + wB.a.value);
   }

   public static void swap(A a, A b){
      A temp = a;
      a = b;
      b = temp;
   }

   public static void swap(Wrapper wA, Wrapper wB){
      A temp = wA.a;
      wA.a = wB.a;
      wB.a = temp;
   }
}
class A {
   public int value;
}
class Wrapper {
   A a;
   Wrapper(A a){ this.a = a;}
}

輸出

1, 2
2, 1

更新於: 23-Jun-2020

350 人觀看

開啟你的 職業 生涯

完成課程獲得認證

開始
廣告