Everything has an expiration date
155 - Java 컬렉션 프레임워크(Collection Framework) : Stack 자료구조에서의 요소 저장(push())과, 요소를 꺼내오는 메소드 peek()과 pop()의 차이 본문
[Java]/Program source (java)
155 - Java 컬렉션 프레임워크(Collection Framework) : Stack 자료구조에서의 요소 저장(push())과, 요소를 꺼내오는 메소드 peek()과 pop()의 차이
Jelly-fish 2023. 9. 21. 15:06/* ======================================================
■■■ 컬렉션 프레임워크(Collection Framework) ■■■
=========================================================*/
import java.util.Stack;
public class Test155
{
// 정적 문자열 배열 선언 및 초기화
private static final String[] colors = {"검정", "노랑", "초록", "파랑", "빨강", "연두"};
// 생성자
public Test155()
{
// st 라는 Stack 자료구조 생성
// 제네릭을 활용하여 자료구조에 담기는 데이터에 대한 표현 → 『<String>』
Stack<String> st = new Stack<String>();
// st 라는 Stack 자료구조에 데이터(colors) 담기
//st = colors; // (Ⅹ)
/*
st.push(colors[0]); // st.add(colors[0]);
st.push(colors[1]); // st.add(colors[0]);
st.push(colors[2]); // st.add(colors[0]);
st.push(colors[3]); // st.add(colors[0]);
st.push(colors[4]); // st.add(colors[0]);
st.push(colors[5]); // st.add(colors[0]);
*/
/*
for (int i = 0; i < colors.length; i++)
{
st.push(colors[i]); // st.add(colors[i]);
}
*/
for (String color : colors)
{
st.push(color); // st.add(color);
}
//st.push(10.0);
//st.push(10); // ★ 제네릭<String> 때문에 실수를 담을 수가 없다!!
// 제네릭 없이 Stack Object 타입이었다면 스택에 충분히 담을 수 있었을 것이다.
//--==>> 에러 발생(컴파일 에러)
//-- 제네릭 표현식을 통해 선언하고 있는
// String 이 아닌 다른 자료형(double 이나 int)을
// 스택 자료구조 st 에 push() 하려고 했기 때문에...
st.push("보라"); // 맨 마지막에 담기므로 맨 처음에 출력된다. (후입선출)
// 출력 메소드 호출
popStack(st);
}
// 출력 메소드
private void popStack(Stack<String> st)
{
System.out.print("pop : ");
//System.out.println(st);
// -> st.peek() → 맨 끝의 요소를 가져오는데 제거를 하지 않기 때문에,
// 연두를 출력하면서 무한 반복한다(제거되지 않으므로... not Empty)
//-- 스택 자료구조가 비었다면...
while (!st.empty()) // isEmpty()
{
System.out.print(st.pop() + " ");
}
System.out.println();
}
public static void main(String[] args)
{
new Test155();
}
}
// 실행 결과
// pop : 연두 빨강 파랑 초록 노랑 검정
// pop : 보라 연두 빨강 파랑 초록 노랑 검정