一、List列表與Set列表的區別
List列表是有序、可以重複、線程不安全的列表,Set是無序、不能重複、線程不安全的列表。但List和Set可以通過方法來轉換爲線程安全的,加互斥鎖。
Set<Long> set=new HashSet<>();
// 轉換爲線程安全的集合
Collections.synchronizedSet(set);
List<Long> lists=new ArrayList<>();
Collections.synchronizedList(lists);
二、List與Set的轉換
1) List轉換爲set
List<Long> ids=new ArrayList<>();
HashSet<Long> set=new HashSet<>(ids);
2) Set轉換爲List
HashSet<Long> set=new HashSet<>();
List<Long> ids=new ArrayList<>(set);
此處都可以使用 addAll()方法來替換。
需要注意的是: List轉換爲Set的時候,當有重複數據時,轉換爲出現數據丟失的情況,因爲Set集合不允許有重複數據。