Java 中 List 和 Set 的区别
javaobject oriented programmingprogramming更新于 2025/7/4 10:52:17
List 和 Set 接口都属于 Collection 框架。这两个接口都扩展了 Collection 接口。它们都用于将对象集合存储为单个单元。
在 jdk1.2 之前,我们曾经使用 Arrays、Vectors 和 Hashtable 将对象分组为单个单元。
| Sr.否。 | Key | List | Set |
|---|---|---|---|
| 1 | 位置访问 | 列表提供对集合中元素的位置访问。 | Set 不提供对集合中元素的位置访问集合 |
| 2 | 实现 | List的实现有ArrayList,LinkedList,Vector,Stack | 集合接口的实现有HashSet和LinkedHashSet |
| 3 | 重复 | 我们可以将重复的元素存储在列表中。 | 我们不能在 Set 中存储重复的元素 |
| 4 | 排序 | List 维护集合中元素的插入顺序 | Set 不维护任何顺序 |
| 5 | 空元素 | 列表可以存储多个空元素 | 集合只能存储一个空元素 |
列表示例
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class ListExample {
public static void main(String[] args) {
List<String> al = new ArrayList<String>();
al.add("BMW");
al.add("Audi");
al.add("BMW");
System.out.println("List Elements: ");
System.out.print(al);
}
}
输出
List Elements: [BMW, Audi, BMW]
集合示例
import java.util.Set;
import java.util.HashSet;
import java.util.TreeSet;
public class SetExample {
public static void main(String args[]) {
int count[] = {2, 4, 3, 5};
Set<Integer> hset = new HashSet<Integer>();
try{
for(int i = 0; i<4; i++){
hset.add(count[i]);
}
System.out.println(hset);
}
catch(Exception e){
e.printStackTrace();
}
}
}
输出
[2, 4, 3, 5]
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

