Skip to content

Instantly share code, notes, and snippets.

@kamatama41
Created October 6, 2012 14:13
Show Gist options
  • Save kamatama41/3845029 to your computer and use it in GitHub Desktop.
Save kamatama41/3845029 to your computer and use it in GitHub Desktop.
オブジェクトの値の書き換え副作用が発生しないことを観察する
package com.kamatama41.sandbox4j;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import org.junit.Test;
public class SafetyCopyTest {
@Test
public void test_オブジェクトの値の書き換え副作用が発生しない() throws Exception {
String str = "e1";
Value value = new Value("v1");
int integer = 1;
SafetyEntity e1 = new SafetyEntity(str, value, integer);
SafetyEntity e2 = new SafetyEntity(str, value, integer);
SafetyEntity e3 = e1.clone();
e1.str = "e3";
e1.value.str = "v3";
e1.integer = 3;
assertThat(e1.str, is("e3"));
assertThat(e1.integer, is(3));
assertThat(e1.value.str, is("v3"));
assertThat(e2.str, is("e1"));
assertThat(e2.integer, is(1));
assertThat(e2.value.str, is("v1")); // 参照元がディープコピーされているため、書き換わらない
assertThat(e3.str, is("e1"));
assertThat(e3.integer, is(1));
assertThat(e3.value.str, is("v1")); // 参照元がディープコピーされているため、書き換わらない
}
private static class SafetyEntity implements Cloneable {
public SafetyEntity(String str, Value value, int integer) {
this.str = str;
this.value = new Value(value.str);
this.integer = integer;
}
private String str;
private Value value;
private int integer;
@Override
public SafetyEntity clone() {
try {
SafetyEntity result = (SafetyEntity)super.clone();
result.value = new Value(value.str);
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
private static class Value {
String str;
public Value(String str) {
this.str = str;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment