第十一章 持有对象

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);
}
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值