stack(栈)
栈(Stack)也是一种特殊的线性表,是一种后进先出(LIFO)的结构。
- 栈是限定仅在表尾进行插入和删除运算的线性表,表尾称为栈顶(top),表头称为栈底(bottom)。
- 栈的物理存储可以用顺序存储结构,也可以用链式存储结构。
Queue(队列)
队列(Queue)是限定所有的插入只能在表的一端进行,而所有的删除都在表的另一端进行的线性表。
- 表中允许插入的一端称为队尾(Rear),允许删除的一端称为队头(Front)。
- 队列的操作是按先进先出(FIFO)的原则进行的。
- 队列的物理存储可以用顺序存储结构,也可以用链式存储结构。
package fourtyFourth;
import java.util.LinkedList;
import java.util.Queue;
public class MyQueue
{
private LinkedList list = new LinkedList();
public void add(Object o)
{
list.addLast(o);
}
public Object poll()
{
return list.removeFirst();
}
public boolean isEmpty()
{
return list.isEmpty();
}
public static void main(String[] args)
{
MyQueue myQueue = new MyQueue();
myQueue.add("one");
myQueue.add("two");
myQueue.add("three");
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
System.out.println(myQueue.isEmpty());
Queue queue = new LinkedList();
queue.add("one");
queue.offer("two");
queue.add("three");
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.peek());
System.out.println(queue.isEmpty());
}
}
结果是
one
two
three
true
one
two
three
false
ArrayList
无参的构造方法我们已经了解了,接下来我们了解下有参的构造方法
- public ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity. (构造一个空的列表使用初始的容量)
initialCapacity - the initial capacity of the list (列表最开始的容量)
建立一个数组列表,该数组有指定的初始容量(capacity)。容量是用于存储元素的基本数组的大小。当元素被追加到数组列表上时,容量会自动增加。 - public ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator. (构造一个列表包含指定集合的元素,顺序是在集合迭代的顺序返回)
c - the collection whose elements are to be placed into this list
建立一个数组列表,该数组列表由类集c中的元素初始化
但是LinkedList只有两个没有第三个,因为没必要
LinkedList
LinkedList list = new LinktedLIst();
list.add("aaa");
- 当向 ArrayList 添加一个对象时,实际上就是将该对象放置到了 ArrayList 底层所维护
的数组当中;当向 LinkedList 中添加一个对象时,实际上 LinkedList 内部会生成一个
Entry 对象,该 Entry 对象的结构为:
Entry{
Entry previous;
Object element;
Entry next;
}
Entry entry = new Entry();
entry.element = "aaa";
lis.add(entry);
其中的 Object 类型的元素 element 就是我们向 LinkedList 中所添加的元素,然后 Entry
又构造好了向前与向后的引用 previous、 next,最后将生成的这个 Entry 对象加入到了链
表当中。 换句话说, LinkedList 中所维护的是一个个的 Entry 对象。