LinkedList是Queue的實現(xiàn)類,是雙向鏈表。決定了LinkedList的節(jié)點都包含了對前一個和后一個節(jié)點的引用。
構造函數(shù)
public LinkedList(); ——生成一個空的鏈表
public LinkedList(Collection<? extends E> c); ——復制構造函數(shù)
常用方法及舉例
- 添加元素:
boolean add(Object element) —— 將元素添加在鏈表的最后
boolean add(int index, Object element) —— 將元素添加在指定位置后面
boolean addFirst(Object element) —— 將元素添加在鏈表的第一個元素的位置
boolean addLast(Object element) —— 將元素添加在鏈表最后
舉例:
package Main;
import java.util.Iterator;
import java.util.LinkedList;
public class Main {
public static void main(String[] args){
LinkedList list = new LinkedList();
list.add(1);
list.add(2);
list.addFirst(0);
list.addLast(4);
list.add(3,3);
Iterator iter = list.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
}
}
}
結果:
0
1
2
3
4
- 獲取鏈表的元素
E get(int index)——獲取索引處的元素
E getFirst()——獲取第一個元素
E getLast()——獲取第最后一個元素
System.out.println(list.getFirst());
System.out.println(list.getLast());
System.out.println(list.get(3));
刪除元素
E remove()——移除鏈表中第一個元素
boolean remove(Object o)——移除鏈表中指定的元素
E remove(int index)——移除鏈表中該索引處的元素
E removeFirst()——移除鏈表中第一個元素
E removeLast()——移除鏈表中最后一個元素
boolean removeFirstOccurrence(Object o)——移除鏈表中第一次出現(xiàn)所在位置的元素
boolean removeLastOccurrence(Object o)——移除鏈表中最后一次出現(xiàn)所在位置的元素其他操作
void push(E e)——與add()效果一樣
E pop()——與remove()效果一樣
E poll()——查詢并移除第一個元素
void clear()——清空集合里的所有元素
Object clone()——復制一個集合
boolean contains(Object object)——判斷集合是否包含指定元素
indexOf(Object o)——返回此列表中首次出現(xiàn)的指定元素的索引,如果此列表中不包含該元素,則返回 -1。
lastIndexOf(Object o)——返回此列表中最后出現(xiàn)的指定元素的索引,如果此列表中不包含該元素,則返回 -1。
例子:
LinkedList myList = new LinkedList();
myList.push("a");
myList.push("b");
myList.push("d");
myList.push("e");
myList.push("f");
System.out.println("myList example");
System.out.println(myList.poll());
myList.pop();
System.out.println(myList.indexOf("e"));
System.out.println(myList.contains("e"));
結果:
myList example
f
-1
false
遍歷
- 普通的for循環(huán)
int size = list.size();
for (int i = 0; i < size; i++) {
System.out.println(list.get(i));
}
- for...each
for (Object j : list) {
System.out.println(j);
}
- 迭代器
for (Iterator<Integer> iter = list.iterator(); iter.hasNext(); ) {
System.out.println(iter.next());
}