Created
March 8, 2012 13:16
-
-
Save froop/2000951 to your computer and use it in GitHub Desktop.
[Java] Cloneableな可変オブジェクトのListのディープコピー
This file contains hidden or 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
import org.apache.commons.lang3.ObjectUtils; | |
private <E extends Cloneable> List<E> copyDeep(List<? extends E> src) { | |
List<E> dest = new ArrayList<E>(); | |
for (E item : src) { | |
dest.add(ObjectUtils.clone(item)); | |
} | |
return dest; | |
} | |
@Test | |
public void testCopyDeepDate() throws ParseException { | |
DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); | |
List<Date> src = new ArrayList<Date>(); | |
src.add(df.parse("2012/03/08")); | |
src.add(df.parse("2012/03/09")); | |
src.add(null); | |
List<Date> dest = copyDeep(src); | |
src.get(0).setTime(new Date().getTime()); | |
src.get(1).setTime(new Date().getTime()); | |
assertEquals(df.parse("2012/03/08"), dest.get(0)); | |
assertEquals(df.parse("2012/03/09"), dest.get(1)); | |
assertNull(dest.get(2)); | |
} | |
@Test | |
public void testCopyDeepSubDate() throws ParseException { | |
List<SubDate> src = new ArrayList<SubDate>(); | |
src.add(new SubDate("2012/03/08")); | |
List<Date> dest = this.<Date>copyDeep(src); | |
src.get(0).setTime(new Date().getTime()); | |
assertEquals(new SubDate("2012/03/08"), dest.get(0)); | |
} | |
private static class SubDate extends Date { | |
private static final long serialVersionUID = 1L; | |
public SubDate(String string) throws ParseException { | |
DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); | |
setTime(df.parse(string).getTime()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment