삽질도사

[안드로이드] 자바 깊은 복사와 얕은 복사 본문

안드로이드

[안드로이드] 자바 깊은 복사와 얕은 복사

전성진블로그 2021. 4. 19. 11:44

1. 얕은 복사(Shallow Copy)

  • 쉽게 말하면 같은 주소 사용하는 거임.
  • 그러므로 복사본의 내용을 바꾸면 원본의 내용도 바뀜

2. 깊은 복사(Deep Copy)

  • 얕은 복사 반대임
  • 싹다 새로운 주소로 만들기 때문에 원본의 내용이 안바뀜
ArrayList<PostInfo> postInfos; //내용이 있다고 치고,

ArrayList<PostInfo> copy; //내용이 없다고 치고,

copy.clear;
copy.Addall(postInfos); // 배열을 비우고 원본을 넣는다고 해도 얕은 복사이다.

//내용이 기본자료형(int,string,..)이면 깊은 복사가 어렵지 않다
//하지만 위에 PostInfo같은 클래스형식의 커스텀 자료형은 깊은복사가 손쉽게 이루어 지지않는다.



 

커스텀 자료형은 개인적으로 필요하다면 애초에 만들 떄 내부에 깊은 복사를 위해서 매서드를 만들어준다.

public class PostInfo implements Parcelable{

    private String title;
    private String contents;
    private ArrayList<String> formats;
    private ArrayList<String> storagePath;
    private String publisher;
    private Date createdAt;
    private String location;
    private String id;
    private String docid;
    private int good;
    private int comment;
    private HashMap<String, Integer> good_user;
    private ArrayList<CommentInfo> comments;
    private String DateFormate_for_layout;

    public PostInfo(PostInfo p) {
        //깊은 복사 전용
        this.title = p.getTitle();
        this.contents = p.getContents();
        this.publisher = p.getPublisher();
        this.createdAt = p.getCreatedAt();
        this.formats = p.getFormats();
        this.id = p.getId();
        this.docid = p.getDocid();
        this.good = p.getGood();
        this.comment = p.getComment();
        this.location = p.getLocation();
        this.storagePath = p.getStoragePath();
        this.good_user = p.getGood_user();
        this.comments = p.getComments();
        this.DateFormate_for_layout = p.DateFormate_for_layout;
    }
    
    ...
}

메인에서는 함수로 만들어서 필요할 때 사용해줌.

//필요할 때에 깊은 복사용 함수를 메인(필요한 곳에서)에서 만들고 사용하는 편.
    public ArrayList<PostInfo> deepCopy(ArrayList<PostInfo> oldone){

        ArrayList<PostInfo> newone = new ArrayList<>(); //복사본 생성

       //내부에 있는 모든 자료형을 new로써 새로운 주소 할당.
        for(int x=0; x<oldone.size(); x++) 
            newone.add(new PostInfo(oldone.get(x))); 
            
        return newone; //복사본 돌려줌
    }