【List】判斷集合相等、集合拷貝
- 【一】判斷集合是否相等
- 【1】☆使用list中的containAll
- 【2】使用for循環遍歷+contains方法
- 【3】將list先排序再轉為String進行比較
- 【4】使用list.retainAll()方法
- 【5】使用MD5加密方式
- 【6】轉換為Java8中的新特性steam流再進行排序來進行比較
- 【二】準備一個判斷集合是否相等的工具類
- 【三】List的深拷貝和淺拷貝
- 【1】什么是淺拷貝(Shallow Copy)和深拷貝(Deep Copy)?
- 【2】淺拷貝
- 【3】深拷貝
- 【4】對象如何實現深拷貝?
- 【四】List如何實現復制
- 【1】淺拷貝
- 【1】循環遍歷復制(含測試方法)
- 【2】使用 List 實現類的構造方法
- 【3】使用 list.addAll() 方法
- 【4】使用 java.util.Collections.copy() 方法
- 【5】使用 Java 8 Stream API 將 List 復制到另一個 List 中
- 【6】在 JDK 10 中的使用方式
- 【2】深拷貝
【一】判斷集合是否相等
【1】☆使用list中的containAll
此方法是判斷list2是否是list的子集,即list2包含于list
//方法一:使用list中的containsAll方法,此方法是判斷list2是否是list的子集,即list2包含于listpublic static void compareByContainsAll(List<String> list,List list2){boolean flag = false;if (list.size()==list2.size()){if (list.containsAll(list2)){flag = true;}}System.out.println("方法一:"+flag);}
【2】使用for循環遍歷+contains方法
//方法二:使用for循環遍歷+contains方法public static void compareByFor(List<String> list,List list2){boolean flag = false;if (list.size()==list2.size()){for (String str :list){if (!list2.contains(str)){System.out.println(flag);return;}}flag = true;}System.out.println("方法二:"+flag);}
【3】將list先排序再轉為String進行比較
(此方法由于涉及同集合內的排序,因此需要該集合內數據類型一致)
//方法三:將list先排序再轉為String進行比較(此方法由于涉及同集合內的排序,因此需要該集合內數據類型一致)public static void compareByString(List<String> list,List list2){boolean flag = false;if (list.size()==list2.size()){//使用外部比較器Comparator進行排序,并利用Java8中新添加的特性方法引用來簡化代碼list.sort(Comparator.comparing(String::hashCode));//使用集合的sort方法對集合進行排序,本質是將集合轉數組,再使用比較器進行排序Collections.sort(list2);if (list.toString().equals(list2.toString())){flag = true;}}System.out.println("方法三:"+flag);}
如果涉及到引用數據的排序比如里面的一個個對象數據,則需要實現Comparable接口,并重寫CompareTo方法,在此方法中指定排序原則
package com.example.demo.utils;import lombok.Data;/*** @author zhangqianwei* @date 2021/9/7 17:25*/
@Data
public class Student implements Comparable<Student>{private int id;private String name;private int age;private String sex;public Student() {}public Student(int id, String name, int age, String sex) {this.id = id;this.name = name;this.age = age;this.sex = sex;}@Overridepublic int compareTo(Student o) {//按照年齡排序int result=this.getAge()-o.getAge();return result;}
}
//如果涉及到引用數據的排序比如里面的一個個對象數據,則需要實現Comparable接口,并重寫CompareTo方法,在此方法中指定排序原則public static void compareBySort(){ArrayList<Student> stus=new ArrayList<Student>();Student stu1=new Student(1,"張三",23,"男");Student stu2=new Student(2,"李四",21,"女");Student stu3=new Student(3,"王五",22,"女");Student stu4=new Student(4,"趙六",22,"女");stus.add(0,stu1);stus.add(1,stu2);stus.add(2,stu3);stus.add(3,stu4);System.out.println("原始順序:"+stus);Collections.sort(stus);System.out.println("排序后:"+stus);}
【4】使用list.retainAll()方法
如果集合list2中的元素都在集合list中則list2中的元素不做移除操作,反之如果只要有一個不在list中則會進行移除操作。即:list進行移除操作返回值為:true反之返回值則為false。
//方法四:使用list.retainAll()方法,此方法本質上是判斷list是否有移除操作,如果list2是list的子集則不進行移除返回false,否則返回true//如果集合list2中的元素都在集合list中則list2中的元素不做移除操作,反之如果只要有一個不在list中則會進行移除操作。即:list進行移除操作返回值為:true反之返回值則為false。public static void compareByRetainAll(List<String> list,List list2){boolean flag = false;if (list.size()==list2.size()){if (!list.retainAll(list2)){flag = true;}System.out.println("方法四:"+flag);}}
【5】使用MD5加密方式
使用MD5加密方式判斷是否相同,這也算是list轉String的一個變化,將元素根據加密規則轉換為String加密字符串具有唯一性故可以進行判斷;
根據唯一性可以想到map中的key也是具有唯一性的,將list中的元素逐個添加進map中作為key然后遍歷比較list2中的元素是否都存在其中,不過這個要求list中的元素不重復
【6】轉換為Java8中的新特性steam流再進行排序來進行比較
public static void compareBySteam(List<String> list,List list2){boolean flag = false;if (list.size() == list2.size()){String steam = list.stream().sorted().collect(Collectors.joining());String steam2 = (String) list2.stream().sorted().collect(Collectors.joining());if (steam.equals(steam2)){flag = true;}}System.out.println("方法六:"+flag);
}
【二】準備一個判斷集合是否相等的工具類
靜態方法,全局調用
package com.example.demo.utils;import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;/*** @author zhangqianwei* @date 2021/10/8 11:46*/
public class compareList {//比較兩個集合是否相同public static void main(String[] args) {List<String> list = new ArrayList<>();list.add("南京");list.add("蘇州");list.add("常州");List list2 = new ArrayList<>();list2.add("常州");list2.add("蘇州");list2.add("南京");compareByContainsAll(list,list2);compareByFor(list,list2);compareByString(list,list2);compareBySort();compareByRetainAll(list,list2);compareBySteam(list,list2);}//方法一:使用list中的containsAll方法,此方法是判斷list2是否是list的子集,即list2包含于listpublic static void compareByContainsAll(List<String> list,List list2){boolean flag = false;if (list.size()==list2.size()){if (list.containsAll(list2)){flag = true;}}System.out.println("方法一:"+flag);}//方法二:使用for循環遍歷+contains方法public static void compareByFor(List<String> list,List list2){boolean flag = false;if (list.size()==list2.size()){for (String str :list){if (!list2.contains(str)){System.out.println(flag);return;}}flag = true;}System.out.println("方法二:"+flag);}//方法三:將list先排序再轉為String進行比較(此方法由于涉及同集合內的排序,因此需要該集合內數據類型一致)public static void compareByString(List<String> list,List list2){boolean flag = false;if (list.size()==list2.size()){//使用外部比較器Comparator進行排序,并利用Java8中新添加的特性方法引用來簡化代碼list.sort(Comparator.comparing(String::hashCode));//使用集合的sort方法對集合進行排序,本質是將集合轉數組,再使用比較器進行排序Collections.sort(list2);if (list.toString().equals(list2.toString())){flag = true;}}System.out.println("方法三:"+flag);}//如果涉及到引用數據的排序比如里面的一個個對象數據,則需要實現Comparable接口,并重寫CompareTo方法,在此方法中指定排序原則public static void compareBySort(){ArrayList<Student> stus=new ArrayList<Student>();Student stu1=new Student(1,"張三",23,"男");Student stu2=new Student(2,"李四",21,"女");Student stu3=new Student(3,"王五",22,"女");Student stu4=new Student(4,"趙六",22,"女");stus.add(0,stu1);stus.add(1,stu2);stus.add(2,stu3);stus.add(3,stu4);System.out.println("原始順序:"+stus);Collections.sort(stus);System.out.println("排序后:"+stus);}//方法四:使用list.retainAll()方法,此方法本質上是判斷list是否有移除操作,如果list2是list的子集則不進行移除返回false,否則返回true//如果集合list2中的元素都在集合list中則list2中的元素不做移除操作,反之如果只要有一個不在list中則會進行移除操作。即:list進行移除操作返回值為:true反之返回值則為false。public static void compareByRetainAll(List<String> list,List list2){boolean flag = false;if (list.size()==list2.size()){if (!list.retainAll(list2)){flag = true;}System.out.println("方法四:"+flag);}}//方法五:使用MD5加密方式判斷是否相同,這也算是list轉String的一個變化,將元素根據加密規則轉換為String加密字符串具有唯一性故可以進行判斷//根據唯一性可以想到map中的key也是具有唯一性的,將list中的元素逐個添加進map中作為key然后遍歷比較list2中的元素是否都存在其中,不過這個要求list中的元素不重復//方法六:轉換為Java8中的新特性steam流再進行排序來進行比較public static void compareBySteam(List<String> list,List list2){boolean flag = false;if (list.size() == list2.size()){String steam = list.stream().sorted().collect(Collectors.joining());String steam2 = (String) list2.stream().sorted().collect(Collectors.joining());if (steam.equals(steam2)){flag = true;}}System.out.println("方法六:"+flag);}}
【三】List的深拷貝和淺拷貝
【1】什么是淺拷貝(Shallow Copy)和深拷貝(Deep Copy)?
淺拷貝只復制某個對象的引用,而不復制對象本身,新舊對象還是共享同一塊內存。深拷貝會創造一個一模一樣的對象,新對象和原對象不共享內存,修改新對象不會改變原對象。
假設 B 復制了 A,當修改 A 時,看 B 是否會發生變化。如果 B 也跟著變了,說明這是淺拷貝,如果 B 沒變,那就是深拷貝。
【2】淺拷貝
對于數據類型是基本數據類型(整型:byte、short、int、long;字符型:char;浮點型:float、double;布爾型:boolean)的成員變量,淺拷貝會直接進行值傳遞,也就是將該屬性值復制一份給新的對象。因為是兩份不同的數據,所以對其中一個對象的該成員變量值進行修改,不會影響另一個對象拷貝得到的數據。
對于數據類型是引用數據類型(比如說成員變量是某個數組、某個類的對象等)的成員變量,淺拷貝會進行引用傳遞,也就是只是將該成員變量的引用值(內存地址)復制一份給新的對象。因為實際上兩個對象的該成員變量都指向同一個實例,在這種情況下,在一個對象中修改該成員變量會影響到另一個對象的該成員變量值。
【3】深拷貝
相對于淺拷貝而言,深拷貝對于引用類型的修改,并不會影響到對應的拷貝對象的值。
備注:一般在討論深拷貝和淺拷貝時,通常是針對引用數據類型而言的。因為基本數據類型在進行賦值操作時(也就是拷貝)是直接將值賦給了新的變量,也就是該變量是原變量的一個副本,這個時候你修改兩者中的任何一個的值都不會影響另一個。而對于引用數據類型來說,在進行淺拷貝時,只是將對象的引用復制了一份,也就是內存地址,即兩個不同的變量指向了同一個內存地址,那么改變任一個變量的值,都是改變這個內存地址所存儲的值,所以兩個變量的值都會改變。
Java 對對象和基本數據類型的處理是不一樣的。在 Java 中,用對象作為入口參數傳遞時,缺省為 “引用傳遞”,也就是說僅僅傳遞了對象的一個”引用”。當方法體對輸入變量修改時,實質上就是直接操作這個對象。 除了在函數傳值的時候是”引用傳遞”,在任何用 ”=” 向對象變量賦值的時候都是”引用傳遞”。
將對象序列化為字節序列后,再通過反序列化即可完美地實現深拷貝。
【4】對象如何實現深拷貝?
Object 對象聲明了 clone() 方法,如下代碼所示。
/*** Creates and returns a copy of this object. The precise meaning* of "copy" may depend on the class of the object. The general* intent is that, for any object {@code x}, the expression:* <blockquote>* <pre>* x.clone() != x</pre></blockquote>* will be true, and that the expression:* <blockquote>* <pre>* x.clone().getClass() == x.getClass()</pre></blockquote>* will be {@code true}, but these are not absolute requirements.* While it is typically the case that:* <blockquote>* <pre>* x.clone().equals(x)</pre></blockquote>* will be {@code true}, this is not an absolute requirement.* <p>* By convention, the returned object should be obtained by calling* {@code super.clone}. If a class and all of its superclasses (except* {@code Object}) obey this convention, it will be the case that* {@code x.clone().getClass() == x.getClass()}.* <p>* By convention, the object returned by this method should be independent* of this object (which is being cloned). To achieve this independence,* it may be necessary to modify one or more fields of the object returned* by {@code super.clone} before returning it. Typically, this means* copying any mutable objects that comprise the internal "deep structure"* of the object being cloned and replacing the references to these* objects with references to the copies. If a class contains only* primitive fields or references to immutable objects, then it is usually* the case that no fields in the object returned by {@code super.clone}* need to be modified.* <p>* The method {@code clone} for class {@code Object} performs a* specific cloning operation. First, if the class of this object does* not implement the interface {@code Cloneable}, then a* {@code CloneNotSupportedException} is thrown. Note that all arrays* are considered to implement the interface {@code Cloneable} and that* the return type of the {@code clone} method of an array type {@code T[]}* is {@code T[]} where T is any reference or primitive type.* Otherwise, this method creates a new instance of the class of this* object and initializes all its fields with exactly the contents of* the corresponding fields of this object, as if by assignment; the* contents of the fields are not themselves cloned. Thus, this method* performs a "shallow copy" of this object, not a "deep copy" operation.* <p>* The class {@code Object} does not itself implement the interface* {@code Cloneable}, so calling the {@code clone} method on an object* whose class is {@code Object} will result in throwing an* exception at run time.** @return a clone of this instance.* @throws CloneNotSupportedException if the object's class does not* support the {@code Cloneable} interface. Subclasses* that override the {@code clone} method can also* throw this exception to indicate that an instance cannot* be cloned.* @see java.lang.Cloneable*/protected native Object clone() throws CloneNotSupportedException;
Object 的 clone() 方法本身是一個淺拷貝的方法,但是我們可以通過實現 Cloneable 接口,重寫該方法來實現深拷貝,除了調用父類中的 clone() 方法得到新的對象, 還要將該類中的引用變量也 clone 出來。如果只是用 Object 中默認的 clone() 方法,是淺拷貝的。
如下代碼所示,我們創建一個測試類 TestClone,實現深拷貝。
package com.example.test;import lombok.Data;
import lombok.SneakyThrows;@Data
public class TestClone implements Cloneable {private String a;// 構造函數TestClone(String str) {this.a = str;}@Overrideprotected TestClone clone() throws CloneNotSupportedException {TestClone newTestClone = (TestClone) super.clone();newTestClone.setA(this.a);return newTestClone;}@SneakyThrowspublic static void main(String[] args) {TestClone clone1 = new TestClone("a");TestClone clone2 = clone1.clone();System.out.println(clone2.a); // aclone2.setA("b");System.out.println(clone1.a); // aSystem.out.println(clone2.a); // b}
}
【四】List如何實現復制
List 復制時有深拷貝和淺拷貝兩類方式,分述如下。
【1】淺拷貝
List 其本質就是數組,而其存儲的形式是地址,如下圖所示。
將 listA 列表淺拷貝為 listB 時,listA 與 listB 指向同一地址,造成的后果就是,改變 listB 的同時也會改變 listA,因為改變listB 就是改變 listB 所指向的地址的內容,由于 listA 也指向同一地址,所以 listA 與 listB 一起改變。其常見的實現方式有如下幾種(以上述代碼中的 TestClone 為測試類)。
【1】循環遍歷復制(含測試方法)
@SneakyThrowspublic static void main(String[] args) {List<TestClone> listA = new ArrayList<>();TestClone testClone = new TestClone("a");listA.add(testClone);System.out.println(listA); // [TestClone(a=a)]List<TestClone> listB = new ArrayList<>(listA.size());for (TestClone clone : listA) {listB.add(clone);}System.out.println(listB); // [TestClone(a=a)]listA.get(0).setA("b");System.out.println(listA); // [TestClone(a=b)]System.out.println(listB); // [TestClone(a=b)]}
【2】使用 List 實現類的構造方法
@SneakyThrows
public static void main(String[] args) {List<TestClone> listA = new ArrayList<>();TestClone testClone = new TestClone("a");listA.add(testClone);List<TestClone> listB = new ArrayList<>(listA);
}
【3】使用 list.addAll() 方法
@SneakyThrowspublic static void main(String[] args) {List<TestClone> listA = new ArrayList<>();TestClone testClone = new TestClone("a");listA.add(testClone);List<TestClone> listB = new ArrayList<>();listB.addAll(listA);}
【4】使用 java.util.Collections.copy() 方法
public static void main(String[] args) {List<TestClone> listA = new ArrayList<>();TestClone clone = new TestClone("a");listA.add(clone);List<TestClone> listB = new ArrayList<>();listB.add(new TestClone("c"));System.out.println(listB); // [TestClone(a=c)]Collections.copy(listB, listA);System.out.println(listB); // [TestClone(a=a)]listA.get(0).setA("b");System.out.println(listA); // [TestClone(a=b)]System.out.println(listB); // [TestClone(a=b)]}
【5】使用 Java 8 Stream API 將 List 復制到另一個 List 中
public static void main(String[] args) {List<TestClone> listA = new ArrayList<>();TestClone clone = new TestClone("a");listA.add(clone);List<TestClone> listB = listA.stream().collect(Collectors.toList());System.out.println(listB); // [TestClone(a=a)]listA.get(0).setA("b");System.out.println(listA); // [TestClone(a=b)]System.out.println(listB); // [TestClone(a=b)]}
【6】在 JDK 10 中的使用方式
public static void main(String[] args) {List<TestClone> listA = new ArrayList<>();TestClone clone = new TestClone("a");listA.add(clone);List<TestClone> listB = List.copyOf(listA);listA.get(0).setA("b");System.out.println(listA); // [TestClone@76ed5528]System.out.println(listA.get(0).getA()); // bSystem.out.println(listB); // [TestClone@76ed5528]System.out.println(listB.get(0).getA()); // b}
【2】深拷貝
如圖,深拷貝就是將 listA 復制給 listB 的同時,給 listB 創建新的地址,再將地址 A 的內容傳遞到地址 B。listA 與 listB 內容一致,但是由于所指向的地址不同,所以各自改變內容不會影響對方。深拷貝時,向新列表添加的是原列表中的元素執行 clone() 方法后的新對象。
@SneakyThrowspublic static void main(String[] args) {List<TestClone> listA = new ArrayList<>();TestClone testClone = new TestClone("a");listA.add(testClone);List<TestClone> listB = new ArrayList<>();listB.add(listA.get(0).clone());System.out.println(listB); // [TestClone(a=a)]listA.get(0).setA("b");System.out.println(listA); // [TestClone(a=b)]System.out.println(listB); // [TestClone(a=a)]}