集合概述
一、List接口
- 有序的集合(存储和取出元素的顺序相同)
- 允许存储重复的元素
- 有索引,可以使用普通的for循环遍历
Vector集合:不建议使用,该集合里面的方法都是同步的,效率慢,已经被ArrayList取代
ArrayList集合:查询数据比较快,但添加和删除数据比较慢,底层基于数组实现
LinkedList集合:查询数据比较慢,但添加和删除数据比较快,底层基于双向链表实现
二、Set接口
- 不允许存储重复的元素
- 没有索引,不能使用普通的for循环遍历
- 无序的集合(存储和取出元素的顺序可能不一致)linkedhashset例外
HashSet集合:按照哈希算法存取数据的,具有非常好的性能
TreeSet集合:可以对Set集合进行排序,默认自然排序(即升序)
三、Set自动排序
- String、Integer都已经默认实现了Comparable接口,自定义类型需要自己实现接口,并重写比较方法ComparableTo();
- 在构造TreeSet或者TreeMap集合的时候给其传一个比较器对象;
- 当比较规则只有一个的时候,建议实现Comparable接口
四、迭代器
迭代器Iterator是一个接口,不能直接调用,只能通过collection集合调用Iterator()方法来获取一个迭代器,通过获取的迭代器来迭代遍历集合中的数据
常用方法:
- hashNext():如果存在下一个元素,则返回true
- next():返回迭代器的下一个元素
五、Map接口
- Map集合Collection集合没有关系
- Map集合以key和value的这种键值对的方式存储元素
- key和value都是存储java对象的内存地址
- 所有的Map集合的key是无序不可重复的,Map集合的key和Set集合存储元素的特点相同
HashMap集合:底层是哈希表数据结构,是非线程安全的
TreeMap集合:底层是二叉树数据结构,key可以自动按照大小顺序排序
六、Map集合的遍历
方式一:采用遍历集合中所有key的方式来间接得到所有的value,通过调用map集合的keyset()方法
方式二:将map集合转换成set集合 ,set集合中的每个元素是一个Node节点,这个node节点里有key和value
通过调用map集合的entrySet()方法转换成set集合