一、List的淺拷貝和深拷貝
在Java中,List是一種常用的數據結構,它可以存儲多個元素。當我們需要將一個List中的元素複製到另一個List中時,有兩種方式:淺拷貝和深拷貝。
淺拷貝只是複製了List中元素的引用,而不是元素本身,這意味着如果複製後的元素髮生了改變,原List中相應的元素也會改變。
深拷貝則是將原List中的元素全部複製一份到新的List中,新List中的元素和原List中的元素是完全獨立的。
// 定義原List List<Person> originalList = new ArrayList<>(); originalList.add(new Person("Tom", 18)); originalList.add(new Person("Lucy", 20)); originalList.add(new Person("Jerry", 22)); // 淺拷貝 List<Person> shallowCopy = new ArrayList<>(originalList); shallowCopy.get(0).setName("Tony"); // 修改拷貝後的元素 System.out.println(originalList.get(0).getName()); // 輸出Tony // 深拷貝 List<Person> deepCopy = new ArrayList<>(); for (Person person : originalList) { deepCopy.add(person.clone()); // 手動克隆原List中的元素並添加到新List中 } deepCopy.get(0).setName("Mary"); // 修改拷貝後的元素 System.out.println(originalList.get(0).getName()); // 輸出Tom
二、使用Java 8的Stream實現List的複製
在Java 8中,我們可以使用Stream實現List的複製。代碼相比傳統for循環會更加簡潔。
List<Person> originalList = new ArrayList<>(); originalList.add(new Person("Tom", 18)); originalList.add(new Person("Lucy", 20)); originalList.add(new Person("Jerry", 22)); // 淺拷貝 List<Person> shallowCopy = originalList.stream().collect(Collectors.toList()); // 深拷貝 List<Person> deepCopy = originalList.stream().map(Person::clone).collect(Collectors.toList());
三、使用Collections.copy()方法實現List的複製
Collections.copy()是Java提供的一個專門用於List複製的方法。不過使用它需要注意幾個問題:
- 必須先創建好目標List,並且其大小必須和原List相等。
- 必須使用ArrayList作為目標List的實現類。
- 原List中的元素必須是實現了Cloneable接口的對象,否則無法進行深拷貝。
List<Person> originalList = new ArrayList<>(); originalList.add(new Person("Tom", 18)); originalList.add(new Person("Lucy", 20)); originalList.add(new Person("Jerry", 22)); // 必須先創建好目標List,並且其大小必須和原List相等 List<Person> targetList = new ArrayList<>(Collections.nCopies(originalList.size(), null)); // 淺拷貝 Collections.copy(targetList, originalList); // 深拷貝(原List中的元素必須是實現了Cloneable接口的對象) for (int i = 0; i < originalList.size(); i++) { targetList.set(i, originalList.get(i).clone()); }
四、結論
List的複製在開發中非常常見,而且也有多種實現方式。我們可以根據實際需求選擇不同的方式來完成複製工作,其中使用Stream可能是最為方便的,但其並不支持深拷貝。深拷貝需要手動遍歷原List並且克隆每一個元素,或者使用Collections.copy()方法。
原創文章,作者:DGOY,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/139612.html