1. 集合类:List、Set、Queue、Map,我们称为容器。他们都可以自动调整大小。
2. 向上转型,ArrayList、LinkedList具有List接口中未包含的额外方法,若你需要使用这些方法,就不能向上转型为更通用的接口。
List<Apple> apples = new ArrayList<Apple>();
List<Apple> apples = new LinkedList<Apple>();
3.各容器包含的类型
在List的起始位置插入和删除元素,那么LinkedList效率高一些,但在中间或者末尾位置上插入和删除元素方面,ArrayList与LinkedList性能相同。
4. 插播一条知识:为什么采用接口-抽象类-具体类三层设计?
因为用接口定义框架,抽象类提供这个接口的部分实现。用户可以简单的定义一个具体类继承自抽象类,而无需实现接口中的所有方法,对用户编写代码提供了方便。
5.
5. Collection接口包含了处理合集(Set、List、Queue)中元素的方法。方法如下表:
注意:这里有toArray()方法,为该合集的元素返回一个Object数组,以后可能会用到。
6.迭代器:Iterator
6.1 Collection与Iterator
由于Collection接口继承自Iterable接口,Iterable接口中定义了iterator()方法,该方法会返回一个迭代器。所以,Collection和Iterator是绑定在一起的。一个类去实现Collection时,必须要提供iterator()的方法。由上图也可以看出Collection与Iterator的关系,并且,Iterator的三个方法也如上图所示。
6.2 foreach与Iterator
foreach方法主要用于数组,但他也可以用于任何Collection对象,并且,遍历Collection对象时的foreach内部也是Iterator实现的。
6.3 创建一个迭代器:
迭代器是一种经典的设计模式。作用:因为迭代器可以用于(List、Set、Map、Queue)等元素的输出,所以他可以在不暴露数据结构的情况下,来遍历该数据结构。看以下代码:
List<Integer> apples = new ArrayList<>();
Iterator<Integer> it = apples.iterator();//iterator()方法返回一个迭代器
6.4 Iterator的使用:
public class Welcome{
class Pet{
}
public static void display(Iterator<Pet> it){
while(it.hasNext()){
Pet p = it.next();
System.out.println(p.id() + ":" + p + " ");
}
System.out.println();
}
public static void main(String[] args) {
ArrayList<Pet> pets = Pets.arrayList(8);
LinkedList<Pet> petsll = new LinkedList<Pet>(pets);
HashSet<Pet> petHS = new HashSet<Pet>(pets);
TreeSet<Pet> petTS = new TreeSet<Pet>(pets);
display(pets.iterator());
display(petsll.iterator());
display(petHS.iterator());
display(petTS.iterator());
}
}
display()方法并不知道容器的确切类型。