table of Contents
LinkedList
LinkedList class extends AbstractSequentialList class and implements List interface;
LinkedList provides a connection list data structure;
1. Constructor
Construction method | Explanation |
---|---|
LinkedList() | Create an empty list of links |
LinkedList(Collection c) | Establishing a connection initiated by a list of elements c |
2. API
In addition to inheriting LinkedList List interface method, and provides the following methods:
Types of | method | Explanation |
---|---|---|
void | addFirst(Object o) | The collection begins with the insertion of the specified element |
void | addLast(Object o) | Inserting the end of the collection specified element |
Object | getFirst() | Returns the first element of the collection |
Object | getLast() | Returns the last element of the collection |
Object | removeFirst() | Removes and returns the first element of the collection |
Object | removeLast() | Removes and returns the last element of the collection |
3. Use of class
- LinkedList additive element sequence and add () related order;
- LinkedList is not synchronized method, multiple threads access a List, must themselves implement access synchronization (ie thread safe);
import java.util.Iterator;
import java.util.LinkedList;
public class test {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.add("apple");
ll.add("banana");
ll.addFirst("cat");
ll.addLast("dog");
Iterator it = ll.iterator();
while (it.hasNext()) {
System.out.print(it.next() + ", ");
}
System.out.println();
System.out.println(ll.getFirst());
System.out.println(ll.getLast());
System.out.println(ll.removeFirst());
System.out.println(ll.removeLast());
ll.add(1, "ball");
Object val = ll.get(2);
ll.set(2, (String) val + " Updated");
it = ll.iterator();
while (it.hasNext()) {
System.out.print(it.next() + ", ");
}
}
}
//输出:
//cat, apple, banana, dog,
//cat
//dog
//cat
//dog
//apple, ball, banana Updated,
4. Comparison of the array
- An array is a contiguous memory space, fast query, add, and delete elements slow;
- Elements of the list are not stored in a row, the next element on a recording address of an element, deletions fast, slow query;