java 기초 공부 내용 정리(컬렉션 프레임웍- 큐, 스택)

홍준성·2022년 6월 3일
0

java 기초 공부

목록 보기
31/39

큐(Queue)

한 쪽 끝에서는 삽입이, 다른 쪽 끝에서는 삭제가 일어나는 구조

큐의 특징

  1. 선입선출(FIFO)의 구조
  2. front: 삭제, rear: 삽입

큐와 관련된 메서드

메서드설명
boolean add(E e)Queue에 요소 e 추가
E element()Queue의 제일 상단 요소 반환
E remove()Queue의 최상단 요소를 반환 후 제거
boolean offer(E e)Queue에 요소 e를 추가
E peek()Queue의 제일 상단 요소 반환
E poll()Queue의 최상단 요소를 반환 후 제거

→ Queue는 인터페이스이므로, 사용하려면 업캐스팅이 필요하다.

큐 사용법

  1. Queue< Element > q = new LinkedList< Element >(); → 주로 사용하는 방법
  2. Queue < Element > q = new Array < Element >();

	public static void main(String[] args) {
		Queue<String> q = new LinkedList<>();
		//1. add: rear위치에 e 삽입
		q.add("apple");
		q.add("banana");
		q.add("cherry");
		q.add("tomato");
		System.out.println(q);
		
		//2. element: front에 위치한 데이터 반환
		System.out.println("element: "+q.element());
		
		//3. remove:front에 위치한 데이터를 반환 후 삭제
		System.out.println("remove: "+q.remove());
		System.out.println(q);
		
		//4. offer(e): rear위치에 데이터 삽입
		q.offer("peach");
		System.out.println("offer: "+q);
		
		//5. peek(): front 위치에 있는 데이터의 값 반환
		System.out.println("peek: "+q.peek());
		
		//6. poll(): front 위치에 있는 데이터를 반환 후 삭제
		System.out.println("poll: "+q.poll());
		System.out.println(q);
	}
}

스택(Stack)

한 쪽 끝에서 삽입과 삭제가 모두 일어나는 구조

스택의 특징

  1. 후입선출(LIFO)의 구조
  2. top: 삽입, 삭제
  3. Vector의 자식 클래스

스택에 관련된 메서드

메서드설명
E peek()top 요소를 반환
E pop()top 요소 제거 후 반환
E push(E item)top에 요소 추가
int search(Object O)요소 O가 있는지 검색해서 위치 반환

→ Stack은 클래스이므로, 바로 사용 가능

	public static void main(String[] args) {

		Stack<String> s = new Stack<String>();
		
		//1. push():데이터 삽입
		s.push("apple");
		s.push("banana");
		s.push("cherry");
		System.out.println(s);
		
		
		//2. pop(): top의 데이터 삭제
		System.out.println("pop: "+s.pop());
		System.out.println(s);
		
		//3. peek(): top의 데이터 보기
		System.out.println("peek: " + s.peek());
		
		//4. search() : 첫 번째가 0이 아니고 1임
		System.out.println(s.search("apple"));
		System.out.println(s.search("banana"));
	}
}
profile
준성이의 개발자 공부 velog

0개의 댓글