天天看點

java vector search_【Java集合系列三】Vector-Stack解析

1 packagejava.util;2

3 /**

4 * The

Stack

class represents a last-in-first-out5 * (LIFO) stack of objects. It extends class Vector with five6 * operations that allow a vector to be treated as a stack. The usual7 * push and pop operations are provided, as well as a8 * method to peek at the top item on the stack, a method to test9 * for whether the stack is empty, and a method to search10 * the stack for an item and discover how far it is from the top.11 *

12 * When a stack is first created, it contains no items.13 *14 *

A more complete and consistent set of LIFO stack operations is15 * provided by the {@linkDeque} interface and its implementations, which16 * should be used in preference to this class. For example:17 *

{@code      

18 * Deque stack = new ArrayDeque();}

19 *20 *@authorJonathan Payne21 *@sinceJDK1.022 */

23 public

24 class Stack extends Vector{25

28 publicStack() {29 }30

31 /**

32 * Pushes an item onto the top of this stack. This has exactly33 * the same effect as:34 *

35 * addElement(item)      

36 *37 *@paramitem the item to be pushed onto this stack.38 *@returnthe

item

argument.39 *@seejava.util.Vector#addElement40 */

41 publicE push(E item) {42 addElement(item);43

44 returnitem;45 }46

47

55 public synchronizedE pop() {56 E obj;57 int len =size();58

59 obj =peek();60 removeElementAt(len - 1);61

62 returnobj;63 }64

65

73 public synchronizedE peek() {74 int len =size();75

76 if (len == 0)77 throw newEmptyStackException();78 return elementAt(len - 1);79 }80

81

87 public booleanempty() {88 return size() == 0;89 }90

91

105 public synchronized intsearch(Object o) {106 int i =lastIndexOf(o);107

108 if (i >= 0) {109 return size() -i;110 }111 return -1;112 }113

114

115 private static final long serialVersionUID = 1224463164541339165L;116 }