2
\$\begingroup\$

Could I make this method for deep copy generic to the Collection type?
That method is so simple and I can't imagine ever needing to change it, so maybe I should just use the "cut / paste" code re-usage design pattern to handle the Collection typing problem?

public class Start {
    public static void main(String[] args) {
        try {
            test();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    static<T> List<T> deepCopy(List<T> listOrg) throws Exception {
        List<T> listCopy = new ArrayList<T>();

        for(T item : listOrg) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(item);

            InputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            T itemCopy = (T) ois.readObject();

            listCopy.add(itemCopy);
        }

        return listCopy;
    } 

    // --- testing ---
    static void test() throws Exception {
        List<StringBuilder> fooOrg = new ArrayList();
        for(int i = 0; i < 5; i++) {
            fooOrg.add(new StringBuilder("number=" + i));
        }

        List<StringBuilder> fooCopy = deepCopy(fooOrg);
        fooCopy.get(0).append("-->altered?");        
        fooCopy.add(new StringBuilder("xtra item"));

        System.out.println("--fooOrg--");
        for(int i = 0; i < fooOrg.size(); i++) {
            System.out.println("#" + i + ":: " + fooOrg.get(i));
        }
        System.out.println();
        System.out.println("---fooCopy---");
        for(int i = 0; i < fooCopy.size(); i++) {
            System.out.println("#" + i + ":: " + fooCopy.get(i));
        }
    }
}
\$\endgroup\$
  • 2
    \$\begingroup\$ Deep copying has been discussed in depth on StackOverflow. None of the approaches are ideal, but serialization has specific, significant issues that you should be aware of before you start relying on this approach. Additionally, there are implementations of deep copying in several public libraries, including Apache Commons. You might be better served using one of them instead. \$\endgroup\$ – Eric Stein Oct 28 '15 at 16:29
  • \$\begingroup\$ @EricStein cool! I'll look at the resources at Apache Commons. I'm sure I'll also find a lot of other useful stuff as well. thanks. \$\endgroup\$ – david Oct 28 '15 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.