아래 2개의 클래스 파일을 작성하고, 메인에서 아래와 같은 실행결과가 나오도록 코딩하시오.
Stack<T> 클래스
멤버변수
int top;
int capacity;
Object[] stck;
멤버함수
생성자 구현
*capacity만큼 Object 배열 생성
public void push ( T item )
*스택의 객체 꺼내옴
StackExample1(실행클래스)
실행화면
*11개의 데이터를 먼저 넣고 예외발생 확인할 것
결과
스택이 꽉 찼네요! 객체를 못 넣어요!
예외 발생으로 프로그램을 정상 종료합니다.
java.lang.ArrayIndexOutOfBoundsException: 10
stringStack에 push된 객체를 pop()을 꺼낸다.
1번째 객체 값 : 고양
2번째 객체 값 : 용인
3번째 객체 값 : 마산
4번째 객체 값 : 창녕
5번째 객체 값 : 구지
6번째 객체 값 : 현풍
7번째 객체 값 : 대구
8번째 객체 값 : 광주
9번째 객체 값 : 부산
10번째 객체 값 : 서울
intStack에 push된 객체를 pop()을 꺼낸다.
1번째 객체 값 : -55
2번째 객체 값 : 1005
3번째 객체 값 : 665
4번째 객체 값 : 528
5번째 객체 값 : 770
6번째 객체 값 : 150
7번째 객체 값 : 301
8번째 객체 값 : 111
스택이 비었네요. 객체가 없어요. null을 출력해요!
9번째 객체 값 : null
스택이 비었네요. 객체가 없어요. null을 출력해요!
10번째 객체 값 : null
코드
class Stack1<T> {
int top;
int capacity;
Object[] stck;
public Stack1(int capacity) {
top = -1;
stck = new Object[capacity];
}
public void push(T item) { //메인에서 top 사용해서 catch throw 처리?
if (top == stck.length - 1) {
System.out.println("스택이 꽉 찼네요! 객체를 못 넣어요!");
System.out.println("예외 발생으로 프로그램을 정상 종료합니다.");
System.out.println("java.lang.ArrayIndexOutOfBoundsException: " + stck.length);
return;
}
top++;
stck[top] = item;
}
public T pop() {
if (top == -1) {
return null;
}
T a = (T) stck[top]; // 먼저 받아오기
top--;
return a;
}
}
public class StackExample1 {
public static void main(String[] args) {
/*
* Scanner sc = new Scanner(System.in); int n=sc.nextInt();
*/
Stack1<String> stringStack = new Stack1<String>(10);
stringStack.push("서울");
stringStack.push("부산");
stringStack.push("광주");
stringStack.push("대구");
stringStack.push("현풍");
stringStack.push("구지");
stringStack.push("창녕");
stringStack.push("마산");
stringStack.push("용인");
stringStack.push("고양");
stringStack.push("한남");
System.out.println("stringStack에 push된 객체를 pop()을 꺼낸다.");
for (int i = 0; i < 10; i++) {
System.out.println((i + 1) + "번째 객체 값 : " + stringStack.pop()); // 왜 i+1?
}
System.out.println();
Stack1<Integer> intStack = new Stack1<Integer>(10);
intStack.push(111);
intStack.push(301);
intStack.push(150);
intStack.push(770);
intStack.push(528);
intStack.push(665);
intStack.push(1005);
intStack.push(-55);
System.out.println("intStack에 push된 객체를 pop()을 꺼낸다.");
for (int i = 0; i < 10; i++) { // stringStack.size()는 컬렉션 아니라서 안 되는 거 알겠는데 .size()는 왜 안 됨?
if (intStack.top == -1) {
System.out.println("스택이 비었네요. 객체가 없어요. null을 출력해요!");
System.out.println((i + 1) + "번째 객체 값 : " + "null");
} else {
System.out.println((i + 1) + "번째 객체 값 : " + intStack.pop()); // 왜 i+1?
}
}
}
}
제네릭 클래스에서는 .size() 사용이 불가능하다.
'Java' 카테고리의 다른 글
| [Java] 자바 컬렉션 ArrayList (21-3) (1) | 2023.09.07 |
|---|---|
| [Java] 자바 컬렉션 ArrayList (21-2) (0) | 2023.09.07 |
| [Java] 제네릭 클래스 예제 (20-5 확인 필요) (0) | 2023.09.07 |
| [Java] 제네릭 클래스 예제 (20-4) (0) | 2023.09.07 |
| [Java] 제네릭 클래스 예제 (20-3) (0) | 2023.09.07 |