List, Set, Map
List:
1. 可以允许重复的元素
2. 可以插入多个null元素
3. 有序
4.ArrayList, LinkedList
Set:
1. 不允许重复对象
2. 只允许一个null元素
3. 无序容器(通常情况)
4. HashSet, LinkedHashSet, TreeSet
Map:
1. Map不是Collection的子接口或者实现类,Map是一个接口
2. key值唯一
3. HashMap, LinkedHashMap, HashTable, TreeMap, ConcurrentHashMap
使用场景
1. 如果经常使用索引来访问或保证有序,使用List;如果经常添加删除,使用LinkedList
2. 如果想保证元素唯一,使用HashSet;如果需要有序,可以使用LinkedHashSet;如果需要自定义排序,可以用TreeSet
3. 如果以键值存储,使用HashMap;如果需要有序,使用TreeMap;线程安全使用HashTable;线程安全又高效使用ConcurrentHashMap
ArrayList和LinkedList效率对比
理论上来讲,LinkedList插入速度应该比较快,下面做实验对比,发现并不完全是这样的。
1. 以一万条数据为基准,测试ArrayList和LinkedList随机插入、头部插入和尾部插入的速度。
由于数据量不是很大,发现速度都差不多,但随机插入速度,ArrayList比LinkedList反而更快点

2. 测试十万条数据
随机插入LinkedList慢很多,头部插入ArrayList比较慢,尾部插入速度差不多

3. 测试一百万条数据
此处随机插入LinkedList速度太慢,不做测试,头部插入ArrayList很慢,尾部插入LinkedList反而慢了

public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new LinkedList<>();
int total = 10000;
Random r = new Random();
long start1 = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
int index = r.nextInt(list1.size() + 1);
list1.add(index, i);
}
long end1 = System.currentTimeMillis();
System.out.printf("ArrayList随机插 %d条数据时间:%d %n", total, end1 - start1);
long start2 = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
int index = r.nextInt(list2.size() + 1);
list2.add(index, i);
}
long end2 = System.currentTimeMillis();
System.out.printf("LinkedList随机插 %d条数据时间:%d %n", total, end2 - start2);
list1.clear();
list2.clear();
long start3 = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
list1.add(0, i);
}
long end3 = System.currentTimeMillis();
System.out.printf("ArrayList头部插 %d条数据时间:%d %n", total, end3 - start3);
long start4 = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
list2.add(0, i);
}
long end4 = System.currentTimeMillis();
System.out.printf("LinkedList头部插 %d条数据时间:%d %n", total, end4 - start4);
list1.clear();
list2.clear();
long start5 = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
list1.add(i);
}
long end5 = System.currentTimeMillis();
System.out.printf("ArrayList尾部插 %d条数据时间:%d %n", total, end5 - start5);
long start6 = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
list2.add(i);
}
long end6 = System.currentTimeMillis();
System.out.printf("LinkedList尾部插 %d条数据时间:%d %n", total, end6 - start6);
}
本文详细介绍了Java集合框架中List、Set和Map的区别与使用场景,包括它们的特点、数据插入性能对比,并提供了具体代码示例。
1131

被折叠的 条评论
为什么被折叠?



