2013-06-01 3 views
0

메신저는 동일한 메모리를 가리 키지 않고 한 배열의 내용을 다른 배열로 복사하려고 시도하지만 위장 할 수 없습니다.배열을 다른 배열로 복사

내 코드 :

class cPrueba { 
    private float fvalor; 

    public float getFvalor() { 
     return fvalor; 
    } 

    public void setFvalor(float fvalor) { 
     this.fvalor = fvalor; 
    } 
} 

List<cPrueba> tListaPrueba = new ArrayList<cPrueba>(); 
List<cPrueba> tListaPrueba2 = new ArrayList<cPrueba>(); 

cPrueba tPrueba = new cPrueba(); 
tPrueba.setFvalor(50); 
tListaPrueba.add(tPrueba); 

tListaPrueba2.addAll(tListaPrueba); 
tListaPrueba2.get(0).setFvalor(100); 

System.out.println(tListaPrueba.get(0).getFvalor()); 

결과는

아직도 동일한 개체를 가리키는 .... "100.0"입니다 ... 어떤 짧은 방법은 복사? (.. (대한 없음) {})

편집 :

class cPrueba implements Cloneable { 
    private float fvalor; 

    public float getFvalor() { 
     return fvalor; 
    } 

    public void setFvalor(float fvalor) { 
     this.fvalor = fvalor; 
    } 

    public cPrueba clone() { 
     return this.clone(); 
    } 
} 

List<cPrueba> tListaPrueba = new ArrayList<cPrueba>(); 
List<cPrueba> tListaPrueba2 = new ArrayList<cPrueba>(); 

cPrueba tPrueba = new cPrueba(); 
tPrueba.setFvalor(50); 
tListaPrueba.add(tPrueba); 

for (cPrueba cp : tListaPrueba) 
    tListaPrueba2.add(cp); 

tListaPrueba2.get(0).setFvalor(100); 

System.out.println(tListaPrueba.get(0).getFvalor()); 

스틸 (

+2

당신은 모든 개체를 복제해야하고, 따라서이를 반복 할 수 있습니다. –

+0

** 배열 ** 또는'ArrayList'? – Runemoro

답변

1

는 dystroy는이처럼 루프를 통해 전달하고 모든 개체를 복제해야합니다, 말했듯이 :

List<cPrueba> newList = new ArrayList<cPrueba>(); 
for (cPrueba cp : oldList) 
    newList.add(cp.clone()); 

을 그리고 그 개체이 복제를 구현 가정, 또는 적어도 방법이라고 클론을 가지고 있어요 .

그래서 아니요, 자신 만의 정적 메서드를 작성하지 않는 한 짧은 방법이 없지만 가능합니다. 당신이 당신의 루프에 cp.clone()를 호출해야합니다, 또한

public cPrueba clone() { 
    cPrueba c = new cPrueba(); 
    c.setFvalor(this.getFvalor()); 
    return c; 
} 

; 당신은 당신의 복제 방법을 필요

편집은 새로운 cPrueba를 반환 add 메소드에 cp를 전달하지 마십시오. 예를 들어, 당신을 위해이 작업을 수행 할 수

tListaPrueba2.add(cp.clone()); 
5

이 방법을 "deepcopy"배열, 또는 Collection 모든 종류의가 없습니다 ... (100)를 얻을 수 (예 : 복사 생성자를 통해) 객체 자체에 딥 카피 지원이없는 경우 을 포함하거나 심지어 Map을 포함 할 수 있습니다.

따라서, 귀하의 질문에 :

어떤 짧은 방법은 복사? ((..) {} 제외)

대답은 없습니다.

물론 개체가 변경되지 않는 경우에는 걱정할 필요가 없습니다.

0

바닐라 자바 ​​

tListaPrueba2.add(cp); 

을 변경합니다.

하지만 그것은 도저 프레임 워크를 끝낼 수있는 몇 가지 향신료를 추가하여

:

http://dozer.sourceforge.net/

관련 문제