@@ -19,42 +19,38 @@ public class Stack<E> implements Serializable {
19
19
/**
20
20
* Position of tail in stack
21
21
*/
22
-
23
22
private int tail = -1 ;
24
23
25
24
/**
26
25
* Size of stack at any given time
27
26
*/
28
-
29
27
private int size ;
30
28
31
29
/**
32
30
* Uninitialized array to hold stack elements.
33
- * WIll be initialized with initial capacity once the object is created
31
+ * Will be initialized with initial capacity once the object is created
34
32
*/
35
- private Object [] elements ;
33
+ private E [] elements ;
36
34
37
35
/**
38
36
* No argument to create stack object with initial capacity
39
37
*/
38
+ @ SuppressWarnings ("unchecked" )
40
39
public Stack () {
41
- elements = new Object [INITIAL_CAPACITY ];
40
+ elements = ( E []) new Object [INITIAL_CAPACITY ];
42
41
}
43
42
44
43
/**
45
44
* Method to check if the given stack is empty or not
46
45
*/
47
-
48
46
public boolean empty () {
49
47
return elements == null || size == 0 ;
50
48
}
51
49
52
-
53
50
/**
54
51
* Method to check the element on head without removing it
55
52
*/
56
-
57
- public Object peek () {
53
+ public E peek () {
58
54
if (empty ()) {
59
55
throw new EmptyStackException ();
60
56
}
@@ -65,13 +61,12 @@ public Object peek() {
65
61
/**
66
62
* Method to remove the top element from stack
67
63
*/
68
-
69
- public Object pop () {
64
+ public E pop () {
70
65
if (empty ()) {
71
66
throw new EmptyStackException ();
72
67
}
73
68
74
- Object removedElement = elements [tail ];
69
+ E removedElement = elements [tail ];
75
70
tail --;
76
71
size --;
77
72
return removedElement ;
@@ -80,29 +75,23 @@ public Object pop() {
80
75
/**
81
76
* Method to add element to stack
82
77
*/
83
- public Object push (Object e ) {
84
-
85
- boolean isSuccess = false ;
86
- if (tail < (INITIAL_CAPACITY - 1 )) {
87
- tail ++;
88
- elements [tail ] = e ;
89
- } else {
90
- Object [] extendedElements = new Object [INITIAL_CAPACITY + EXTENDED_CAPACITY ];
91
- System .arraycopy (elements , 0 , extendedElements , 0 , (tail + 1 ));
78
+ @ SuppressWarnings ("unchecked" )
79
+ public void push (E e ) {
80
+
81
+ tail = tail + 1 ;
82
+ if (tail >= INITIAL_CAPACITY ) {
83
+ E [] extendedElements = (E []) new Object [INITIAL_CAPACITY + EXTENDED_CAPACITY ];
84
+ System .arraycopy (elements , 0 , extendedElements , 0 , tail );
92
85
elements = extendedElements ;
93
- tail ++;
94
- elements [tail ] = e ;
95
86
}
96
- size ++;
97
- return e ;
98
-
87
+ elements [tail ] = e ;
88
+ size = size + 1 ;
99
89
}
100
90
101
91
/**
102
92
* Method to search for an element in stack
103
93
*/
104
-
105
- public int search (Object o ) {
94
+ public int search (E o ) {
106
95
107
96
int index = -1 ;
108
97
boolean found = false ;
@@ -111,7 +100,7 @@ public int search(Object o) {
111
100
}
112
101
113
102
for (int i = 0 ; i < size (); i ++) {
114
- if (elements [i ] == o ) {
103
+ if (elements [i ]. equals ( o ) ) {
115
104
index = i ;
116
105
found = true ;
117
106
break ;
0 commit comments