How to clone ArrayList and also clone its contents?

后端 未结 21 1880
小鲜肉
小鲜肉 2020-11-21 06:42

How can I clone an ArrayList and also clone its items in Java?

For example I have:

ArrayList dogs = getDogs();
ArrayList

        
21条回答
  •  旧巷少年郎
    2020-11-21 07:04

    A nasty way is to do it with reflection. Something like this worked for me.

    public static  List deepCloneList(List original) {
        if (original == null || original.size() < 1) {
            return new ArrayList<>();
        }
    
        try {
            int originalSize = original.size();
            Method cloneMethod = original.get(0).getClass().getDeclaredMethod("clone");
            List clonedList = new ArrayList<>();
    
            // noinspection ForLoopReplaceableByForEach
            for (int i = 0; i < originalSize; i++) {
                // noinspection unchecked
                clonedList.add((T) cloneMethod.invoke(original.get(i)));
            }
            return clonedList;
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            System.err.println("Couldn't clone list due to " + e.getMessage());
            return new ArrayList<>();
        }
    }
    

提交回复
热议问题