注:图片出自《Core Java SE 9 for the Impatient》java
全部的集合接口都是泛型类型的,鼓励在代码中尽量地使用接口,一般Collection、List、Map就足够了。
例如:在构造一个ArrayList后,将引用储存在一个List类型的变量中:框架
List<String> words = new ArrayList<>();
dom
List是一个有序的集合。ArrayList类和LinkedList类实现了List接口。LinkedList插入操做很快————你只须要"拼接"节点便可。可是要达到链表中间会很缓慢,由于你须要从头节点开始遍历全部节点。ArrayList实现了RandomAccess接口,用来代表其支持快速(一般是固定时间)随机访问,而且ArrayList用for或者foreach访问更快。spa
在Set中,元素不会被插入特定的位置,而且不容许重复元素,能够高效地检测一个值是否是它的元素,当顺序可有可无时,Set颇有用。
HashSet和TreeSet类都是实现了Set接口,若是想按顺序遍历集合,则可使用TreeSet。code
Map储存键值对,HashMap和TreeMap都实现了Map接口,HashMap类不保证映射的顺序,特别是它不保证该顺序恒久不变,若是须要按顺序访问键的话,则使用TreeMap。blog
例子:获取一个键对应的值接口
Map<String, Integer> counts = new HashMap<>(); counts.put("Alice", 1); //若是键不存在的话,则get方法将会返回null,int不能为null,当get的返回值进行拆箱操做时,会致使NullPointerException。 int count = counts.get("Alice"); 改进版: //这样,若是键不存在,也会返回0。 int count = counts.getOrDefault("Alice", 0);
Collection的父接口Iterable<T>定义了一个方法:Iterator<T> iterator()
图片
能够用它来访问全部元素:element
Collection<String> coll =...; Iterator<String> iter = coll.iterator(); while (iter.hasNext()){ String element = iter.next(); //处理element } 这个例子中,能够直接使用foreach: for(String element : coll){ //处理element }
Iterator接口也提供了一个remove方法,能够移除以前访问的元素。rem
while (iter.hasNext()){ String element = iter.next(); if(element fulfills the condition) iter.remove(); } 然而,使用removeIf方法更容易: coll.removeIf(e -> e fulfills the condition)