Created
October 6, 2012 13:11
-
-
Save kamatama41/3844908 to your computer and use it in GitHub Desktop.
オブジェクトの値の書き換えで副作用が発生するのを観察する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kamatama41.sandbox4j; | |
import static org.hamcrest.CoreMatchers.is; | |
import static org.junit.Assert.assertThat; | |
import org.junit.Test; | |
public class DangerousCopyTest { | |
@Test | |
public void test_オブジェクトの値の書き換えで副作用が発生する() throws Exception { | |
String str = "e1"; | |
Value v = new Value("v1"); | |
int integer = 1; | |
DangerousEntity e1 = new DangerousEntity(str, v, integer); | |
DangerousEntity e2 = new DangerousEntity(str, v, integer); | |
DangerousEntity 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("v3")); // 参照元が書き換えられている | |
assertThat(e3.str, is("e1")); | |
assertThat(e3.integer, is(1)); | |
assertThat(e3.value.str, is("v3")); // 参照元が書き換えられている | |
} | |
private static class DangerousEntity implements Cloneable { | |
public DangerousEntity(String str, Value value, int integer) { | |
this.str = str; | |
this.value = value; | |
this.integer = integer; | |
} | |
String str; | |
Value value; | |
int integer; | |
@Override | |
public DangerousEntity clone() { | |
try { | |
return (DangerousEntity)super.clone(); | |
} 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