溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

在Java中交換對象數據的方法

發布時間:2020-08-20 15:15:33 來源:億速云 閱讀:272 作者:小新 欄目:編程語言

這篇文章主要介紹在Java中交換對象數據的方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

                                                           假設我們有一個名為“Car”的類,它具有一些屬性。我們創建了Car的兩個對象,car1和car2,如何交換car1和car2的數據?

一個簡單的解決方案是交換成員。例如,如果類Car只有一個integer(整數)屬性“no”(Car number),我們可以通過簡單地交換兩輛車的成員來交換汽車。

class Car 
{ 
    int no; 
    Car(int no) { this.no = no; } 
} 
  
class Main 
{  
    public static void swap(Car c1, Car c2) 
    { 
        int temp = c1.no; 
        c1.no = c2.no; 
        c2.no = temp; 
    } 
    
    public static void main(String[] args) 
    { 
        Car c1 = new Car(1); 
        Car c2 = new Car(2); 
        swap(c1, c2); 
        System.out.println("c1.no = " + c1.no); 
        System.out.println("c2.no = " + c2.no); 
    } 
}

輸出:

c1.no = 2
c2.no = 1

如果我們不知道Car的成員呢?

上面的解決方案是有效的,因為我們知道Car中有一個成員“no”。如果我們不知道Car的成員或者成員列表太大怎么辦。這是一種非常常見的情況,因為使用其他類的類可能無法訪問其他類的成員。下面的解決方案有效嗎?

class Car 
{ 
    int model, no; 
  
    Car(int model, int no) 
    { 
        this.model = model; 
        this.no = no; 
    } 
  
    void print() 
    { 
        System.out.println("no = " + no + 
                           ", model = " + model); 
    } 
} 
  
class Main 
{ 
    public static void swap(Car c1, Car c2) 
    { 
        Car temp = c1; 
        c1 = c2; 
        c2 = temp; 
    } 
  
    public static void main(String[] args) 
    { 
        Car c1 = new Car(101, 1); 
        Car c2 = new Car(202, 2); 
        swap(c1, c2); 
        c1.print(); 
        c2.print(); 
    } 
}

輸出:

no = 1, model = 101
no = 2, model = 202

從上面的輸出中我們可以看到,沒有交換對象。參數在Java中是通過值傳遞的。因此,當我們將c1和c2傳遞給swap()時,swap()函數會創建這些引用的副本。

解決方案是使用Wrapper類如果我們創建一個包含Car引用的包裝類,我們可以通過交換Wrapper類的引用來交換Car。

class Car 
{ 
    int model, no; 
  
    Car(int model, int no) 
    { 
        this.model = model; 
        this.no = no; 
    } 
  
    void print() 
    { 
        System.out.println("no = " + no +  
                           ", model = " + model); 
    } 
} 
  
class CarWrapper 
{ 
   Car c; 
  
   CarWrapper(Car c)   {this.c = c;} 
} 
  
class Main 
{ 
    public static void swap(CarWrapper cw1,  
                            CarWrapper cw2) 
    { 
        Car temp = cw1.c; 
        cw1.c = cw2.c; 
        cw2.c = temp; 
    } 
  
    public static void main(String[] args) 
    { 
        Car c1 = new Car(101, 1); 
        Car c2 = new Car(202, 2); 
        CarWrapper cw1 = new CarWrapper(c1); 
        CarWrapper cw2 = new CarWrapper(c2); 
        swap(cw1, cw2); 
        cw1.c.print(); 
        cw2.c.print(); 
    } 
}

輸出:

no = 2, model = 202
no = 1, model = 101

因此,即使user 類無法訪問要交換對象的類的成員,Wrapper類解決方案仍然有效。

以上是在Java中交換對象數據的方法的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女