In our earlier tutorial we have seen how to use default Stack class in Java and their methods like push, pop, peek etc., Suppose in any of the interview if interviewer asked us to implement our own Stack class which holds any type of data like Integer, String or even other datatypes. Then we need to go with Generics and need to implement our Stack class. |
|
Lets see simple example to implement Stack using ArrayList and using Generics for holding any datatype.
import java.util.ArrayList;
public class MyStack <E> {
ArrayList<E> list = null;
public MyStack() {
list = new ArrayList<E>();
}
public E push(E val){
list.add(val);
return val;
}
public E pop(){
E val = list.get(list.size()-1);
list.remove(list.size()-1);
return val;
}
public E peek(){
E val = list.get(list.size()-1);
return val;
}
public int size(){
return list.size();
}
public int search(E val){
int id = -1;
if(list.contains(val)){
id = list.indexOf(val);
}
return id;
}
public boolean empty(){
if(list.size() == 0) return true;
else return false;
}
@Override
public String toString() {
return list.toString();
}
}
Our Stack class is ready and we can test with below code.
public class TestMyStack {
public static void main(String[] args) {
MyStack<Integer> stack = new MyStack<Integer>();
int stkSize = stack.size();
System.out.println("STACK SIZE : "+stkSize);
//PUSH
stack.push(11);
stack.push(21);
stack.push(31);
stack.push(41);
stack.push(51);
stkSize = stack.size();
System.out.println("STACK SIZE : "+stkSize);
//STACK
System.out.println("STACK : "+stack);
//PEEK
System.out.println("PEEK : "+stack.peek());
//POP
System.out.println("POP : "+stack.pop());
stkSize = stack.size();
System.out.println("STACK SIZE : "+stkSize);
//PEEK
System.out.println("PEEK : "+stack.peek());
//EMPTY
System.out.println("EMPTY : "+stack.empty());
//SEARCH
System.out.println("SEARCH : "+stack.search(21));
//SEARCH
System.out.println("SEARCH : "+stack.search(700));
}
}
OUTPUT:
STACK SIZE : 0
STACK SIZE : 5
STACK : [11, 21, 31, 41, 51]
PEEK : 51
POP : 51
STACK SIZE : 4
PEEK : 41
EMPTY : false
SEARCH : 1
SEARCH : -1