donaricano-btn

스택(Stack) - 제네릭스택(Stack Using Generic)


- 제네릭을 이용하여 String, int 등 다양하게 받을 수 있다


1. 구현

1) 초기화

1
2
3
4
5
6
7
8
9
10
11
public class StackUsingGeneric <T extends Object>{
     
    private int stackSize;
    private int top;
    private T[] stackArr;
     
    public StackUsingGeneric(int size){
        this.stackSize = size;
        this.top = -1;
        this.stackArr = (T[]) new Object[stackSize];
    }

- T 로 선언하여 객체 형태의 따라 받을 수 있게 한다

2) push(), isStackFull(), increaseCapacity()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void push(T element){
    if(this.isStackFull()){
        System.out.println("Stack is full");
        this.increaseCapacity();
    }
    System.out.println("adding:"+element);
    this.stackArr[++top] = element;
}
public boolean isStackFull(){
    return (this.stackSize -1 == top);
}
 
public void increaseCapacity(){
      
    T[] newArr = (T[]) new Object[stackSize * 2];
    for(int i = 0; i<stackSize; i++){
        newArr[i] = stackArr[i];
    }
    this.stackArr = newArr;
    this.stackSize = this.stackSize *2;
}
 

3) pop(), isStackEmpty(), peek()

1
2
3
4
5
6
7
8
9
10
11
12
13
public T pop()throws Exception{
    if(this.isStackEmpty()){
        throw new Exception("Stack is empty");
    }
    System.out.println("removing:"+stackArr[top]);
    return stackArr[top--];
     
}
 
public T peek(){
    System.out.println("peeking:"+this.stackArr[top]);
    return this.stackArr[top];
}
 

4) main()

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
public static void main(String[]args){
    StackUsingGeneric<Integer> a1 = new StackUsingGeneric(2);
    try{
        a1.push(1);
        a1.push(2);
        a1.peek();
        a1.push(3);
        a1.pop();
         
    }catch(Exception e){
        System.out.print(e.getMessage());
    }
     
    StackUsingGeneric<String> a2 = new StackUsingGeneric(2);
    try{
        a2.push("a");
        a2.push("b");
        a2.peek();
        a2.push("c");
        a2.pop();
         
    }catch(Exception e){
        System.out.print(e.getMessage());
    }
}
 

- 객체를 String, Integer 두개로 생성

블로그 이미지

리딩리드

,