code

Java 배열에 대한 복제 방법

codestyles 2020. 12. 25. 09:53
반응형

Java 배열에 대한 복제 방법


Java의 clone () 메서드가 배열에서 사용될 때 정확히 무엇을 반환합니까? 원본에서 복사 한 데이터로 새 어레이를 반환합니까?

전의:

int[] a = {1,2,3};
int[] b = a.clone();

clone방법은 어레이에 호출, 상기 광원 어레이와 같은 요소를 포함 (또는 참조) 새로운 어레이에 대한 참조를 반환한다.

따라서 귀하의 예에서는 int[] a힙에 생성 된 별도의 개체 인스턴스이고 힙에 생성 된 int[] b별도의 개체 인스턴스입니다. (모든 배열은 객체임을 기억하십시오).

    int[] a = {1,2,3};
    int[] b = a.clone();

    System.out.println(a == b ? "Same Instance":"Different Instance");
    //Outputs different instance

수정 하면 두 개체가 별도의 개체 인스턴스이므로 int[] b변경 사항이 반영되지 않습니다 int[] a.

    b[0] = 5;
    System.out.println(a[0]);
    System.out.println(b[0]);
    //Outputs: 1
    //         5

이것은 소스 배열에 객체가 포함되어있을 때 약간 더 복잡해집니다. clone메서드는 소스 배열과 동일한 개체를 참조하는 새 배열에 대한 참조를 반환합니다.

그래서 우리가 수업이 있다면 Dog...

    class Dog{

        private String name;

        public Dog(String name) {
            super();
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }

유형의 배열을 만들고 채 웁니다 Dog.

    Dog[] myDogs = new Dog[4];

    myDogs[0] = new Dog("Wolf");
    myDogs[1] = new Dog("Pepper");
    myDogs[2] = new Dog("Bullet");
    myDogs[3] = new Dog("Sadie");

그런 다음 복제 개 ...

    Dog[] myDogsClone = myDogs.clone();

배열은 동일한 요소를 참조합니다 ...

    System.out.println(myDogs[0] == myDogsClone[0] ? "Same":"Different");
    System.out.println(myDogs[1] == myDogsClone[1] ? "Same":"Different");
    System.out.println(myDogs[2] == myDogsClone[2] ? "Same":"Different");
    System.out.println(myDogs[3] == myDogsClone[3] ? "Same":"Different");
    //Outputs Same (4 Times)

즉, 복제 된 배열을 통해 액세스 한 객체를 수정하면 동일한 참조를 가리 키기 때문에 소스 배열의 동일한 객체에 액세스 할 때 변경 사항이 반영됩니다.

    myDogsClone[0].setName("Ruff"); 
    System.out.println(myDogs[0].getName());
    //Outputs Ruff

그러나 어레이 자체를 변경하면 해당 어레이에만 영향을 미칩니다.

    myDogsClone[1] = new Dog("Spot");
    System.out.println(myDogsClone[1].getName());
    System.out.println(myDogs[1].getName());
    //Outputs Spot
    //        Pepper

If you generally understand how object references work, it is easy to understand how arrays of objects are impacted by cloning and modifications. To gain further insight into references and primitives I would suggest reading this excellent article.

Gist of Source Code


clone() method creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:

 x.clone() != x

Will be true, and that the expression:

 x.clone().getClass() == x.getClass()

Will be true, but these are not absolute requirements.

While it is typically the case that:

 x.clone().equals(x)

will be true, this is not an absolute requirement.

By convention, the returned object should be obtained by calling super.clone. If a class and all of its superclasses (except Object) obey this convention, it will be the case that x.clone().getClass() == x.getClass().

ReferenceURL : https://stackoverflow.com/questions/14149733/clone-method-for-java-arrays

반응형