跳到主要內容

通過與C++程序對比,徹底搞清楚JAVA的對象拷貝

目錄

  • 一、背景

  • 二、JAVA對象拷貝的實現

    • 2.1 淺拷貝

    • 2.2 深拷貝的實現方法一

    • 2.3 深拷貝的實現方法二

      • 2.3.1 C++拷貝構造函數

      • 2.3.2 C++源碼

      • 2.3.3 JAVA通過拷貝構造方法實現深拷貝



  • 四、總結



一、背景


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();

};


留言

這個網誌中的熱門文章

強強聯手!攜手打造雲林縣Web3.0 領地方品牌進軍元宇宙

中華電信攜手國內最大Potato Media Web3.0社群共享平台,及品牌醫生果俐文創三方結合,透過經濟部「CBMP智慧雲遊跨域串連計畫」,協助品牌數位轉型,帶動品牌體驗情境、新商業模組升級與行動支付應用,第一站選在雲林縣當地原生消費品牌,打造社群消費循環,探索近期最夯的元宇宙新玩法。 Potato Media執行長顏宏霖表示,在CBMP計畫協助下,加上站內Web3.0資源,將快速協助雲林縣當地品牌升級轉型,幫助店家創造品牌價值,包含黑矸仔醬油、四代目麥芽酥、玉津烘焙坊、禪屋米胖工坊、YuDS沐耳飲、莫蒂精品巧克力、維野納複合式餐飲、頂雲咖啡、媽祖埔豆腐張、玉山碾米廠等,另外嘉義市麥麵、名香茗茶也等不及跨縣市加入,結合Potato Media站內活動,打造雲林專屬限定NFT道具與頭框,發行雲林扭蛋,體驗全新元宇宙新世界。 左起雲林縣計畫處處長李明岳、果俐文創執行長-陳郁涵、雲林縣議員周秀月、中華電信雲林營運處總經理張肇家、Potato Media執行長顏宏霖、LINE禮物代表睿鼎數位、12CMTaiwan行銷總監楊涵柔。(圖/由Potato Media提供) 此次Potato Media平台合作內容是店家會員註冊活動:首次註冊可得100積分 + 一顆扭蛋,店家推薦文章介紹,可領取店家消費優惠券,站內扭蛋禮物抽獎活動,獎項豐富:雲林限定禮品、雲林意象限定NFT道具與頭框,雲林幣扭一下APP政令大聲公獎勵活動,另外各種雲林美食伴手禮、住宿旅遊的店家,都可以使用行動支付或上LINE禮物平台實際體驗消費。 推薦評價好的 iphone維修 中心 擁有專業的維修技術團隊,同時聘請資深iphone手機維修專家,現場說明手機問題,快速修理,沒修好不收錢 產品缺大量曝光嗎?你需要的是一流 包裝設計 窩窩觸角包含自媒體、自有平台及其他國家營銷業務等,多角化經營並具有國際觀的永續理念。 雲林縣副縣長謝淑亞強調,此次計畫和Potato Media 合作,Potato Media 是一個在 2021 年 4 月正式發布的「區塊鏈 Web3.0 共享社群平台」,創作者和使用者都可以透過互動的機制,例如對文章點讚、留言與轉發分享,來獲取相對應比例的加密貨幣CFO(Potato Media 平台上的原生加密貨幣),跟Facebook、Instagram、YouTu...

要上網站行銷農產品,得經過市政府抽驗農藥殘留,檢驗合格才能上網行銷

台北網站設計      網頁設計公司     網站設計公司 食安五環為「源頭控管」、「重建生產管理履歷」、「提高查驗能力」、「加重生產者、廠商的責任」及「鼓勵、創造監督平臺」五大要環,除推動政府與市民消費者共同監督食品安全,更要從農場到餐桌,鏈結農村產業線,以網路社群為媒介,建立嘉義市農村網頁平台。活動現場介紹「農抵嘉」產銷網頁平台的內容,包含在地人文地產景,將景觀、產業、生態及文化等資訊整合、展現,更推廣在地農村農友優質、安全的農產品。要上「農抵嘉」網站行銷農產品,得經過市政府抽驗農藥殘留,檢驗合格才能上網行銷自己的農產品,嘉義市農友可以多利用,也提供店家採購管道。 「尚安心,農抵嘉」,透過「農抵嘉」產銷網頁平台,鏈結農村產業線並促進地產地消,從源頭管理食安,讓政府管理、民間參與,透過食安小教育,讓小朋友接觸農作物,與生產者互動,產生共鳴,一同攜手維護嘉義市的食安。記者會中也展示紅瓦厝社區所做的紅瓦窯烤,並有其他下埤花生等農產品,透過農場職人使「農特產品不只是農產品」,民眾可登入「農抵嘉」網頁http://chiayirural.com/index.asp瞭解更進一步的訊息。 網動廣告 參考資料:蕃新聞https://n.yam.com/Article/20171226529712 Orignal From: 要上網站行銷農產品,得經過市政府抽驗農藥殘留,檢驗合格才能上網行銷

IEA:疫情衝擊能源需求 但再生能源呈創紀錄成長_台中搬家公司

※ 台中搬家公司 教你幾個打包小技巧,輕鬆整理裝箱! 還在煩惱搬家費用要多少哪?台中大展搬家線上試算搬家費用,從此不再擔心「物品怎麼計費」、「多少車才能裝完」 摘錄自2020年11月10日中央社報導 國際能源總署(IEA)報告今天(10日)指出,武漢肺炎(COVID-19)疫情可能衝擊能源需求,但電力部門再生能源繼續以創紀錄速度成長。 IEA執行董事比羅爾(Fatih Birol)表示:「在2025年,再生能源將成為全球最大發電來源,預計將提供1/3的全球電力,終結煤炭50年來作為最大電力供應來源的地位。」 ※推薦 台中搬家公司 優質服務,可到府估價 台中搬鋼琴,台中金庫搬運,中部廢棄物處理,南投縣搬家公司,好幫手搬家,西屯區搬家 IEA關於再生能源的年度報告估計,儘管受到疫情干擾,今年的再生能源新發電容量可望創紀錄,達將近200GW(GW為十億瓦)。 能源轉型 國際新聞 再生能源 疫情看氣候與能源 本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理 ※ 台中搬家公司 教你幾個打包小技巧,輕鬆整理裝箱! 還在煩惱搬家費用要多少哪?台中大展搬家線上試算搬家費用,從此不再擔心「物品怎麼計費」、「多少車才能裝完」 Orignal From: IEA:疫情衝擊能源需求 但再生能源呈創紀錄成長_台中搬家公司