1. Java构造器
1.1 概念
构造器:又叫构造方法、构造函数。当new一个对象的时候,就会调用构造器。
默认构造器:如果没有定义构造器,那么会默认一个无参构造器,当然如果自定义了构造器,则会覆盖默认的无参构造器。注意,在实际中,我们定义类的时候,最好手动定义一个无参构造器。
构造器重载:跟普通方法一样,构造器也支持重载。就是说在定义一个类的时候,可以同时定义多个带参数的构造器,它是通过不同的参数列表来实现重载的。
构造器的继承:子类的构造器会默认调用父类的无参构造器,如果父类没有无参构造器,则必须在子类构造器的第一行通过super关键字指定调用父类的其他构造器。
2. 迭代器
迭代器模式:就是提供一种方法对一个容器对象中的各个元素进行访问,而又不暴露该对象容器的内部细节。
2.1 概述
Java集合框架的集合类,我们有时候称之为容器,这是数据容器。容器的种类很多,比如ArrayList、LinkedList、HashSet等,每种容器都有自己的特点,ArrayList底层维护的是一个数组,LinkedList是链表结构,HashSet是哈希表,每种容器都有自己的数据结构。
因为容器的内部结构不同,很多时候时候可能不知道怎么去遍历容器中的元素。而数据容器的操作在很多时候都具有极大的共性,于是Java采用了迭代器为各种容器提供公共的操作接口,使得对容器的遍历操作完全与其底层相隔离,可以到达极好的解耦效果,所以Java引入了迭代器模式。
对于数组我们使用下标来进行处理
1 int array[] = new int[3];
2 for (int i = 0; i < array.length; i++) {
3 System.out.println(array[i]);
4 }
对ArrayList的处理
1 List<String> list = new ArrayList<String>();
2 for(int i = 0 ; i < list.size() ; i++){
3 String string = list.get(i);
4 }
对于这两种方式,我们总是都知道它的内部结构,访问代码和集合本身是紧密耦合的,无法将访问逻辑从集合类和客户端代码中分离出来。不同的集合会对应不同的遍历方法,客户端代码无法复用。在实际应用中如何将上面两个集合整合是相当麻烦的。所以才有Iterator,它总是用同一种逻辑来遍历集合。使得客户端自身不需要来维护集合的内部结构,所有的内部状态都由Iterator来维护。客户端不用直接和集合进行打交道,而是控制Iterator向它发送向前向后的指令,就可以遍历集合。
2.2 实现原理
1. java.util.Iterator
这里我们看Java中的Iterator接口是如何实现的?
在Java中Iterator为一个接口,它只提供了迭代的基本规则。源码的解释如下:
An iterator over a collection. {@code Iterator} takes the place of
* {@link Enumeration} in the Java Collections Framework. Iterators
* differ from enumerations in two ways:
*
* <ul>
* <li> Iterators allow the caller to remove elements from the
* underlying collection during the iteration with well-defined
* semantics.
* <li> Method names have been improved.
* </ul>
这段话的意思翻译过来是说,Iterator是对Collection进行迭代的迭代器。迭代器取代了Java Collection Framework中的枚举类Enumeration。迭代器与枚举有两点不同:
1. 迭代器在迭代期间可以从集合中移除元素。
2. 方法名得到了改进,Enumeration的方法名称都比较长。
package java.util;
public interface Iterator<E> {
boolean hasNext();//判断是否存在下一个对象元素
E next();//获取下一个元素
//移除元素
default void remove() {
throw new UnsupportedOperationException("remove");
}
}
2. Iterable
这里,我们先把源码附上:
public interface Iterable<T> {
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
Iterator<T> iterator();
/**
* Performs the given action for each element of the {@code Iterable}
* until all elements have been processed or the action throws an
* exception. Actions are performed in the order of iteration, if that
* order is specified. Exceptions thrown by the action are relayed to the
* caller.
* <p>
* The behavior of this method is unspecified if the action performs
* side-effects that modify the underlying source of elements, unless an
* overriding class has specified a concurrent modification policy.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for (T t : this)
* action.accept(t);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 1.8
*/
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
}
Java中还提供了一个Iterable接口,它有一个方法 Iterator iterator(); Iterable接口用这个方法返回一个迭代器,我们常用的是实现了该接口的子接口有:Collection、List、Set等。实现Iterable接口允许对象成为Foreach语句的目标,就可以通过foreach语句来遍历你的底层序列。
Iterable接口包含这个方法Iterator iterator();,并且Iterable被foreach方法用来在序列中移动。因此如果创建了实现Iterable接口的类,都可以将它用于foreach中。
使用迭代器遍历集合:
public static void main(String[] args) {
2 List<String> list = new ArrayList<String>();
3 list.add("张三1");
4 list.add("张三2");
5 list.add("张三3");
6 list.add("张三4");
7
8 List<String> linkList = new LinkedList<String>();
9 linkList.add("link1");
10 linkList.add("link2");
11 linkList.add("link3");
12 linkList.add("link4");
13
14 Set<String> set = new HashSet<String>();
15 set.add("set1");
16 set.add("set2");
17 set.add("set3");
18 set.add("set4");
19 //使用迭代器遍历ArrayList集合
20 Iterator<String> listIt = list.iterator();
21 while(listIt.hasNext()){
22 System.out.println(listIt.next());
23 }
24 //使用迭代器遍历Set集合
25 Iterator<String> setIt = set.iterator();
26 while(setIt.hasNext()){
27 System.out.println(setIt.next());
28 }
29 //使用迭代器遍历LinkedList集合
30 Iterator<String> linkIt = linkList.iterator();
31 while(linkIt.hasNext()){
32 System.out.println(linkIt.next());
33 }
34 }
使用foreach遍历集合
List<String> list = new ArrayList<String>();
list.add("张三1");
list.add("张三2");
list.add("张三3");
list.add("张三4");
for (String string : list) {
System.out.println(string);
}
从这里很明显可以看出,使用foreach遍历集合的优势在于代码更加的简洁,更不容易出错,不用关心下标的起始值和终止值