- 因为List是接口,并且所有类型的列表都实现了这个接口,也就是说List定义了列表的所有的标准操作方法。这也是为了封装程序或者方法内部实现,
比如你定一个方法test,返回一个List对象,你在方法内部可以定义为List list=new ArrayList();return list;而其它调用该方法的代码只知道返回的是一个List对象,并不关心它的内部结构,只要它提供列表所有的标准操作就行了,而在以后的维护过程中你发现ArrayList这种结构并不适合你的程序,想换成LinkedList或者是RoleList或者是你自定义结构的List(实现List接口的自定义列表类),那么你只需在test方法内部修改List list=new LinkedList();return list;这个时候所有调用test方法的外部代码都不需要改动,因为它们根本就不知道List的内部结构已经发生了变化,并且它们也不关心发生了什么变化,它们只需要List就行了。
因为List只是接口,实现List接口的不只是ArrayList,还有其他容器类,例如Vector。如果你用ArrayList list = new ArrayList(),那就失去了通用性,使用List,你就可以不必关注用的是ArrayList,还是Vector。例如在下面的代码中
List getList(){
List list = new ArrayList();
return list;
}
客户程序不必关心你用的是ArrayList还是Vector,哪天你因为需要改成
List getList(){
List list = new Vector();
return list;
}
客户程序并不受影响,你的方法的返回值也不必改变,但如果你用
Vector getList(){
Vector list = new Vector();
return list;
}
你看,首先你的方法的返回值必须作相应改变,调用该方法的客户程序也得改,这可能牵涉一系列改动,而用List则省去了这些麻烦。
从这个例子可以推而广之,在new一个新对象时,左边尽量使用接口,以保持代码的最大灵活性。
源程序
import java.util.ArrayList;
import java.util.List;
//"static void main" must be defined in a public class.
class MyQueue {
// store elements
// a pointer to indicate the start position
private List<Integer> data;//!!!定义接口!!!!
private int p_start;
public MyQueue() {
data = new ArrayList<Integer>();
p_start = 0;
}
/** Insert an element into the queue. Return true if the operation is successful. */
public boolean enQueue(int x) {
data.add(x);
return true;
};
/** Delete an element from the queue. Return true if the operation is successful. */
public boolean deQueue() {
if (isEmpty() == true) {
return false;
}
p_start++;
return true;
}
/** Get the front item from the queue. */
public int Front() {
return data.get(p_start);
}
/** Checks whether the queue is empty or not. */
public boolean isEmpty() {
return p_start >= data.size();
}
};
public class soratraining {
public static void main(String[] args) {
MyQueue q = new MyQueue();
q.enQueue(5);
q.enQueue(3);
if (q.isEmpty() == false) {
System.out.println(q.Front());
}
q.deQueue();
if (q.isEmpty() == false) {
System.out.println(q.Front());
}
q.deQueue();
if (q.isEmpty() == false) {
System.out.println(q.Front());
}
}
}