1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class Vector<E> extends AbstractList<E> implements List<E>{

protected Object[] elementData;//new Object[10]{"杨勇1","杨勇2","杨勇3".....}
protected int elementCount;//3

public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}

public synchronized int size() {
return elementCount;
}

//index - 2
public synchronized E elementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
}

return elementData(index);
}

//index - 2
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}

//index - 2
public synchronized void removeElementAt(int index) {
modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Stack<E> extends Vector<E> {

public Stack() {
}

//item - 杨勇3
public E push(E item) {
addElement(item);

return item;
}

public boolean empty() {
return size() == 0;
}

public synchronized E pop() {
E obj;
int len = size();//len - 3

obj = peek();//obj - "杨勇3"
removeElementAt(len - 1);

return obj;
}

public synchronized E peek() {
int len = size();//len - 3

if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Test01 {

public static void main(String[] args) {

Stack<String> stack = new Stack<>();

stack.push("杨勇1");
stack.push("杨勇2");
stack.push("杨勇3");

while(!stack.empty()){
String pop = stack.pop();
System.out.println(pop);
}
}
}