1. java中数据结构。
数据结构,就是对在内存中的数据的一种安排。java中的数据结构就是对在java内存中的数据的一种安排。java中常用的数据结构有list, set, map等。java中数据结构主要分为两大类,一类是存储单值的collection.另外一类是存储key-value的map.
collection 接口,collection 接口中主要是list 和set. 其他的数据结构都是由这两个接口衍生出来的。Map接口,map的主要实现类有hashMap,treeMap和hashTable。具体结构如下:
2. java中对于数据结构的支持。
ArrayList,其底层是使用数组来实现的,所以该数据结构查找速度与其他list比较而言相对较快,
private transient Object[] elementData;
LinkedList, 其底层是使用链表来实现的,LinkedList的类里面只声明head和tail两个变量。同过这两个变量可以遍历到list里面的所有的值。正因为有这样的实现,所以查找速度比较慢。但是由于插入新的数据的时候,只需更改链表前后相关元素,所以插入和删除速度较快。
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
Vector, vector的实现跟ArrayList一样,只不过是vector是线程安全的,也就是说在ArrayList的一些方法加上了synchronized关键字。
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
如果要使用线程安全的ArrayList,还有另外一种办法可以考虑,使用collections类:
List ls=Collections.synchronizedList(new ArrayList());
Stack, Stack是vector的子类,也就是说,stack具有vector的所有方法之外又多了一些stack特有的方法,push,pop和peek。
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
Queue, java中的queue又细分为blockingqueue和deque,deque就是双向队列。blockingqueue就是当存储和查询条件不满足的时候,进入阻塞状态,直到满足操作条件为止。
Blockingqueue 的实现类主要有ArrayBlockingQueue和linkedBlockingQueue。正如其名称一样,ArrayBlockingQueue和ArrayList的底层实现一样,都是用数组来实现的,LinkedBlockingQueuehe 和LinkedList的底层实现一样。
ArrayBlockingQueue
/** The queued items */
final Object[] items;
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return extract();
} finally {
lock.unlock();
}
}
LinkedBlockingQueue
static class Node<E> {
E item;
/**
* One of:
* - the real successor Node
* - this Node, meaning the successor is head.next
* - null, meaning there is no successor (this is the last node)
*/
Node<E> next;
Node(E x) { item = x; }
}
Dequeue也比较类似,Deque的实现类有Array和linked,不过,java里面没有linkedDeque,而是linkedList,
关于Set和map的实现将在下一篇文章中讨论。