通過與C++程式對比,徹底搞清楚JAVA的物件拷貝

智慧zhuhuix發表於2020-06-11

一、背景

JAVA程式設計中的物件一般都是通過new進行建立的,新建立的物件通常是初始化的狀態,但當這個物件某些屬性產生變更,且要求用一個物件副本來儲存當前物件的“狀態”,這時候就需要用到物件拷貝的功能,以便封裝物件之間的快速克隆。

二、JAVA物件拷貝的實現

2.1 淺拷貝
  • 被複制的類需要實現Clonenable介面;
  • 覆蓋clone()方法,呼叫super.clone()方法得到需要的複製物件;
  • 淺拷貝對基本型別(boolean,char,byte,short,float,double.long)能完成自身的複製,但對於引用型別只對引用地址進行拷貝。
    -- 下面我們用一個例項進行驗證:
    在這裡插入圖片描述
/**
 * 單隻牌
 *
 * @author zhuhuix
 * @date 2020-06-10
 */
public class Card implements Comparable, Serializable,Cloneable {

    // 花色
    private String color = "";
    //數字
    private String number = "";

    public Card() {
    }

    public Card(String color, String number) {
        this.color = color;
        this.number = number;
    }

    public String getColor() {
        return this.color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getNumber() {
        return this.number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    @Override
    public String toString() {
        return this.color + this.number;
    }

    @Override
    public int compareTo(Object o) {
        if (o instanceof Card) {
            int thisColorIndex = Constant.COLORS.indexOf(this.getColor());
            int anotherColorIndex = Constant.COLORS.indexOf(((Card) o).getColor());
            int thisNumberIndex = Constant.NUMBERS.indexOf(this.getNumber());
            int anotherNumberIndex = Constant.NUMBERS.indexOf(((Card) o).getNumber());

            // 大小王之間相互比較: 大王大於小王
            if ("JOKER".equals(this.color) && "JOKER".equals(((Card) o).getColor())) {
                    return thisColorIndex > anotherColorIndex ? 1 : -1;
            }

            // 大小王與數字牌之間相互比較:大小王大於數字牌
            if ("JOKER".equals(this.color) && !"JOKER".equals(((Card) o).getColor())) {
                return 1;
            }
            if (!"JOKER".equals(this.color) && "JOKER".equals(((Card) o).getColor())) {
                return -1;
            }

            // 數字牌之間相互比較: 數字不相等,數字大則牌面大;數字相等 ,花色大則牌面大
            if (thisNumberIndex == anotherNumberIndex) {
                return thisColorIndex > anotherColorIndex ? 1 : -1;
            } else {
                return thisNumberIndex > anotherNumberIndex ? 1 : -1;
            }

        } else {
            return -1;
        }
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
/**
 * 撲克牌常量定義
 *
 * @author zhuhuix
 * @date 2020-06-10
 */
public class Constant {

    // 紙牌花色:黑桃,紅心,梅花,方塊
    final static List<String> COLORS = new ArrayList<>(
            Arrays.asList(new String[]{"♢", "♣", "♡", "♠"}));
    // 紙牌數字
    final static List<String> NUMBERS = new ArrayList<>(
            Arrays.asList(new String[]{"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}));
    // 大王小王
    final static List<String> JOKER = new ArrayList<>(
            Arrays.asList(new String[]{"小王","大王"}));
}

/**
 * 整副副撲克牌
 *
 * @author zhuhuix
 * @date 2020-06-10
 */
public class Poker implements Cloneable, Serializable {

    private List<Card> cards;

    public Poker() {
        List<Card> cardList = new ArrayList<>();
        // 按花色與數字組合生成52張撲克牌
        for (int i = 0; i < Constant.COLORS.size(); i++) {
            for (int j = 0; j < Constant.NUMBERS.size(); j++) {
                cardList.add(new Card(Constant.COLORS.get(i), Constant.NUMBERS.get(j)));
            }
        }
        // 生成大小王
        for (int i = 0; i < Constant.JOKER.size(); i++) {
            cardList.add(new Card("JOKER", Constant.JOKER.get(i)));
        }

        this.cards = cardList;
    }

   
    // 從整副撲克牌中抽走大小王
    public void removeJoker() {
        Iterator<Card> iterator = this.cards.iterator();
        while (iterator.hasNext()) {
            Card cardJoker = iterator.next();
            if (cardJoker.getColor() == "JOKER") {
                iterator.remove();
            }
        }
    }

    public List<Card> getCards() {
        return cards;
    }

    public void setCards(List<Card> cards) {
        this.cards = cards;
    }

    public Integer getCardCount() {
        return this.cards.size();
    }

    @Override
    public String toString() {
        StringBuilder poker = new StringBuilder("[");
        Iterator<Card> iterator = this.cards.iterator();
        while (iterator.hasNext()) {
            poker.append(iterator.next().toString() + ",");
        }
        poker.setCharAt(poker.length() - 1, ']');
        return poker.toString();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

/**
 * 測試程式
 *
 * @author zhuhuix
 * @date 2020-6-10
 */
public class PlayDemo {

    public static void main(String[] args) throws CloneNotSupportedException {

        // 生成一副撲克牌並洗好牌
        Poker poker1 = new Poker();
        System.out.println("新建:第一副牌共 "+poker1.getCardCount()+" 張:"+poker1.toString());

        Poker poker2= (Poker) poker1.clone();
        System.out.println("第一副牌拷頁生成第二副牌,共 "+poker2.getCardCount()+" 張:"+poker2.toString());

        poker1.removeJoker();

        System.out.println("====第一副牌抽走大小王后====");
        System.out.println("第一副牌還有 "+poker1.getCardCount()+" 張:"+poker1.toString());
        System.out.println("第二副牌還有 "+poker2.getCardCount()+" 張:"+poker2.toString());

    }

}
  • 執行結果:
    -- 在第一副的物件中抽走了“大小王”,克隆的第二副的物件的“大小王”竟然也被“抽走了”
    在這裡插入圖片描述
    在這裡插入圖片描述
2.2 深拷貝的實現方法一
  • 被複制的類需要實現Clonenable介面;
  • 覆蓋clone()方法,自主實現引用型別成員的拷貝複製。
    -- 我們只要改寫一下Poker類中的clone方法,讓引用型別成員實現複製:
/**
 * 整副副撲克牌--自主實現引用變數的複製
 *
 * @author zhuhuix
 * @date 2020-06-10
 */
public class Poker implements Cloneable, Serializable {

    private List<Card> cards;

    public Poker() {
        List<Card> cardList = new ArrayList<>();
        // 按花色與數字組合生成52張撲克牌
        for (int i = 0; i < Constant.COLORS.size(); i++) {
            for (int j = 0; j < Constant.NUMBERS.size(); j++) {
                cardList.add(new Card(Constant.COLORS.get(i), Constant.NUMBERS.get(j)));
            }
        }
        // 生成大小王
        for (int i = 0; i < Constant.JOKER.size(); i++) {
            cardList.add(new Card("JOKER", Constant.JOKER.get(i)));
        }

        this.cards = cardList;
    }

    // 從整副撲克牌中抽走大小王
    public void removeJoker() {
        Iterator<Card> iterator = this.cards.iterator();
        while (iterator.hasNext()) {
            Card cardJoker = iterator.next();
            if (cardJoker.getColor() == "JOKER") {
                iterator.remove();
            }
        }
    }

    public List<Card> getCards() {
        return cards;
    }

    public void setCards(List<Card> cards) {
        this.cards = cards;
    }

    public Integer getCardCount() {
        return this.cards.size();
    }

    @Override
    public String toString() {
        StringBuilder poker = new StringBuilder("[");
        Iterator<Card> iterator = this.cards.iterator();
        while (iterator.hasNext()) {
            poker.append(iterator.next().toString() + ",");
        }
        poker.setCharAt(poker.length() - 1, ']');
        return poker.toString();
    }

	// 遍歷原始物件的集合,對生成的物件進行集合複製
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Poker newPoker = (Poker)super.clone();
        newPoker.cards = new ArrayList<>();
        newPoker.cards.addAll(this.cards);
        return newPoker;
    }
}

  • 輸出結果:
    -- 通過自主實現引用型別的複製,原物件與物件的拷貝的引用型別成員地址不再關聯
    在這裡插入圖片描述
2.3 深拷貝的實現方法二
  • 在用第二種方式實現JAVA深拷貝之前,我們首先對C++程式的物件拷貝做個瞭解:
2.3.1 C++拷貝建構函式

C++拷貝建構函式,它只有一個引數,引數型別是本類的引用,且一般用const修飾
在這裡插入圖片描述

2.3.2 C++原始碼
// 單隻牌的類定義
// Created by Administrator on 2020-06-10.
//

#ifndef _CARD_H
#define _CARD_H

#include <string>

using namespace std;

class Card {
private :
    string color;
    string number;
public:
    Card();

    Card(const string &color, const string &number);

    const string &getColor() const;

    void setColor(const string &color);

    const string &getNumber() const;

    void setNumber(const string &number);

    string toString();

};


#endif //_CARD_H

// 單隻牌類的實現
// Created by Administrator on 2020-06-10.
//

#include "card.h"

Card::Card(){}

Card::Card(const string &color, const string &number) : color(color), number(number) {}

const string &Card::getColor() const {
    return color;
}

void Card::setColor(const string &color) {
    Card::color = color;
}

const string &Card::getNumber() const {
    return number;
}

void Card::setNumber(const string &number) {
    Card::number = number;
}


string Card::toString() {
    return getColor()+getNumber();
}




// 撲克牌類的定義
// Created by Administrator on 2020-06-10.
//

#ifndef _POKER_H
#define _POKER_H

#include <vector>
#include "card.h"

using namespace std;

const int COLOR_COUNT=4;
const int NUMBER_COUNT=13;
const int JOKER_COUNT=2;

const string COLORS[COLOR_COUNT] = {"♢", "♣", "♡", "♠"};
const string NUMBERS[NUMBER_COUNT]={"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
const string JOKER[JOKER_COUNT] ={"小王","大王"};

class Poker {
private:
    vector<Card> cards;
public:
    Poker();

    Poker(const Poker &poker);

    const vector<Card> &getCards() const;

    void setCards(const vector<Card> &cards);

    int getCardCount();

    void toString();

    void clear();
};


#endif //_POKER_H

// 撲克牌類的實現
// Created by zhuhuix on 2020-06-10.
//

#include "Poker.h"
#include <iostream>

const vector<Card> &Poker::getCards() const {
    return this->cards;
}

void Poker::setCards(const vector<Card> &cards) {
    Poker::cards = cards;
}

// 建構函式
Poker::Poker() {
    for (int i = 0; i < NUMBER_COUNT; i++) {
        for (int j = 0; j < COLOR_COUNT; j++) {
            this->cards.emplace_back(COLORS[j], NUMBERS[i]);
        }
    }
    for (int i = 0; i < JOKER_COUNT; i++) {
        this->cards.emplace_back("JOKER", JOKER[i]);
    }
}

// 拷貝建構函式
Poker::Poker(const Poker &poker) {
    for (int i = 0; i < poker.getCards().size(); i++) {
        this->cards.emplace_back(poker.cards[i].getColor(), poker.cards[i].getNumber());
    }
}

int Poker::getCardCount() {
    return this->cards.size();
}

void Poker::toString() {
    cout << "共" << getCardCount() << "張牌:";
    cout << "[";
    for (int i = 0; i < this->cards.size(); i++) {
        cout << this->cards[i].toString();
        if (i != getCardCount() - 1) {
            cout << ",";
        }
    }
    cout << "]" << endl;

}

void Poker::clear() {
    this->cards.clear();
}

// 主測試程式
// Created by Administrator on 2020-06-10.
//

#include "Poker.h"
#include <iostream>

using namespace std;

int main() {
    Poker poker1;
    cout << "第一副牌:";
    poker1.toString();
    // 通過拷貝建構函式生成第二副牌
    Poker poker2(poker1);
    cout << "第二副牌:";
    poker2.toString();
    // 清除撲克牌1
    poker1.clear();
    cout << "清空後,第一副牌:";
    poker1.toString();
    cout << "第二副牌:";
    poker2.toString();
    return 0;
}
  • 輸出:
    在這裡插入圖片描述
2.3.3 JAVA通過拷貝構造方法實現深拷貝
  • JAVA拷貝構造方法與C++的拷貝建構函式相同,被複制物件的類需要實現拷貝構造方法:
    --首先需要宣告帶有和本類相同型別的引數構造方法
    --其次拷貝構造方法可以通過序列化實現快速複製
  • 拷貝物件通過呼叫拷貝構造方法進行建立。
    -- 我們再改寫一下Poker類,實現拷貝構造方法:
/**
 * 整副副撲克牌--實現拷貝構造方法
 *
 * @author zhuhuix
 * @date 2020-06-10
 */
public class Poker implements Serializable {

    private List<Card> cards;

    public Poker() {
        List<Card> cardList = new ArrayList<>();
        // 按花色與數字組合生成52張撲克牌
        for (int i = 0; i < Constant.COLORS.size(); i++) {
            for (int j = 0; j < Constant.NUMBERS.size(); j++) {
                cardList.add(new Card(Constant.COLORS.get(i), Constant.NUMBERS.get(j)));
            }
        }
        // 生成大小王
        for (int i = 0; i < Constant.JOKER.size(); i++) {
            cardList.add(new Card("JOKER", Constant.JOKER.get(i)));
        }

        this.cards = cardList;
    }

    // 拷貝構造方法:利用序列化實現深拷貝
    public Poker(Poker poker) {

        try {

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(poker);

            ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(is);
            this.cards = ((Poker) ois.readObject()).getCards();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    // 從整副撲克牌中抽走大小王
    public void removeJoker() {
        Iterator<Card> iterator = this.cards.iterator();
        while (iterator.hasNext()) {
            Card cardJoker = iterator.next();
            if (cardJoker.getColor() == "JOKER") {
                iterator.remove();
            }
        }
    }

    public List<Card> getCards() {
        return cards;
    }

    public void setCards(List<Card> cards) {
        this.cards = cards;
    }

    public Integer getCardCount() {
        return this.cards.size();
    }

    @Override
    public String toString() {
        StringBuilder poker = new StringBuilder("[");
        Iterator<Card> iterator = this.cards.iterator();
        while (iterator.hasNext()) {
            poker.append(iterator.next().toString() + ",");
        }
        poker.setCharAt(poker.length() - 1, ']');
        return poker.toString();
    }
}

  • 對測試主程式進行修改:
/**
 * 測試程式
 *
 * @author zhuhuix
 * @date 2020-6-10
 */
public class PlayDemo {

    public static void main(String[] args) throws CloneNotSupportedException {

        // 生成一副撲克牌並洗好牌
        Poker poker1 = new Poker();
        System.out.println("新建:第一副牌共 "+poker1.getCardCount()+" 張:"+poker1.toString());

        Poker poker2 = new Poker(poker1);
        System.out.println("第一副牌拷頁生成第二副牌,共 "+poker2.getCardCount()+" 張:"+poker2.toString());

        poker1.removeJoker();

        System.out.println("====第一副牌抽走大小王后====");
        System.out.println("第一副牌還有 "+poker1.getCardCount()+" 張:"+poker1.toString());
        System.out.println("第二副牌還有 "+poker2.getCardCount()+" 張:"+poker2.toString());


        Poker poker3 = new Poker(poker1);
        System.out.println("第三副牌還有 "+poker3.getCardCount()+" 張:"+poker3.toString());
    }

}
  • 輸出結果:
    --通過序列化的有手段,同樣也能實現物件的深拷貝
    在這裡插入圖片描述

四、總結

  • java程式進行物件拷貝時,如果物件的類中存在引用型別時,需進行深拷貝
  • 物件拷貝可以通過實現Cloneable介面完成
  • java程式設計也可仿照 C++程式的拷貝建構函式,實現拷貝構造方法進行物件的複製
  • 通過序列化與反序化手段可實現物件的深拷貝

相關文章