ArrayList:底層是一個數組,擅長數據的查找(訪問)
LinkedList:底層鏈表,擅長數據的修改(包括數據添加和刪除)
特點:存儲的數據時有序的(有序是指存儲順序),存放重複的數據,可以存放NULL值
List: add() set() remove get() contains():判斷指定值是否存在,存在返回true,不存在返回false
從下圖中可以看出,ArrayList與LinkedList都是List接口的實現類,因此都實現了List的所有未實現的方法,只是實現的方式有所不同,(編程思想: 從中可以看出面向接口的好處, 對於不同的需求就有不同的實現!),而List接口繼承了Collection接口,Collection接口又繼承了Iterable接口,因此可以看出List同時擁有了Collection與Iterable接口的特性.
二、認識和理解ArrayList
ArrayList實現了List接口,它是以數組的方式來實現的,數組的特性是可以使用索引的方式來快速定位對象的位置,因此對於快速的隨機取得對象的需求,使用ArrayList實現執行效率上會比較好.
ArrayListDemo
public class ArrayListDemo {
public static void main(String[] args) {
List<String> userlist = new ArrayList<String>();
userlist.add("yulon");
userlist.add("xiaoyun");
userlist.add("羽龍共舞");
System.out.println("使用普通for循環:");
for(int i=0; i<userlist.size(); i++){
System.out.print(userlist.get(i)+" ");
}
System.out.println();
System.out.println();
System.out.println("使用Iterator迭代器:");
Iterator it = userlist.iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
System.out.println();
System.out.println("使用增強for循環:");
for(String s : userlist){
System.out.print(s+" ");
}
}
}
這裏列舉出了循環List列表的三種方式: 使用普通for循環,用get方法獲取; 使用Iterator迭代器,使用next方法遍歷;使用增強for循環,直接輸出! 由此可見第三種方法是最方便,最簡潔的!
LinkedList是採用鏈表的方式來實現List接口的,它本身有自己特定的方法,如: addFirst(),addLast(),getFirst(),removeFirst()等. 由於是採用鏈表實現的,因此在進行insert和remove動作時在效率上要比ArrayList要好得多!適合用來實現Stack(堆棧)與Queue(隊列),前者先進後出,後者是先進先出.
public class StringStack {
private LinkedList<String> linkedList
= new LinkedList<String>();
/**
* 將元素加入LinkedList容器
* (即插入到鏈表的第一個位置)
*/
public void push(String name){
linkedList.addFirst(name);
}
/**
* 取出堆棧中最上面的元素
* (即取出鏈表linkedList的第一個元素)
* @return
*/
public String getTop(){
return linkedList.getFirst();
}
/**
* 取出並刪除最上面的元素
* (即移出linkedList的第一個元素)
* @return
*/
public String pop(){
return linkedList.removeFirst();
}
/**
* 獲取元素個數
* @return
*/
public int size(){
return linkedList.size();
}
/**
* 判斷堆棧是否爲空
* (即判斷 linkedList是否爲空)
* @return
*/
public boolean isEmpty(){
return linkedList.isEmpty();
}
//測試
public static void main(String[] args) {
StringStack stack = new StringStack();
stack.push("yulon");
stack.push("xiaoyun");
stack.push("羽龍共舞");
System.out.print("第一個元素是:\t");
System.out.println(stack.getTop());
System.out.println();
System.out.println("全部元素:");
while(!stack.isEmpty()){
System.out.println("\t"+stack.pop());
}
}
}
輸出結果是:第一個元素是: 羽龍共舞
全部元素:
羽龍共舞
xiaoyun
yulon
在刪除可插入對象的動作時,爲什麼ArrayList的效率會比較低呢?
解析: 因爲ArrayList是使用數組實現的,若要從數組中刪除或插入某一個對象,需要移動後段的數組元素,從而會重新調整索引順序,調整索引順序會消耗一定的時間,所以速度上就會比LinkedList要慢許多. 相反,LinkedList是使用鏈表實現的,若要從鏈表中刪除或插入某一個對象,只需要改變前後對象的引用即可!