Learn & Record
[코리아IT아카데미] Java - Stack, Queue (스택, 큐), Set, HashSet 본문
LIFO와 FIFO 컬렉션
- 후입선출 LIFO : 나중에 넣은 객체가 먼저 나가는 구조
- 선입선출 FIFO : 먼저 넣은 객체가 먼저 나가는 구조
1) Stack
- Stack 클래스는 LIFO 자료구조를 구현한 클래스
리턴 타입 | 메소드 | 설명 |
E | push(E Item) | 주어진 개체를 스택에 넣음 |
E | peek() | 스택의 맨 위 객체를 가져옴. 제거 X |
E | pop() | 스택의 맨 위 객체를 가져옴. 제거 O |
2) 실습
import java.util.ArrayList;
class MyStack {
// push, peek, pop
private ArrayList<String> arrayStack = new ArrayList<>();
public void push(String data) { // 스택의 맨 뒤에 요소를 추가
arrayStack.add(data);
}
public String pop() {
int len = arrayStack.size(); // 저장된 개수
if (len == 0) {
System.out.println("스택이 비었습니다.");
return null;
}
return (arrayStack.remove(len-1)); // 맨 뒤에 있는 자료 반환하고 배열에서 제거
}
public String peek() {
int len = arrayStack.size(); // 저장된 개수
if (len == 0) {
System.out.println("스택이 비었습니다.");
return null;
}
return (arrayStack.get(len-1)); // 맨 뒤에 있는 자료 반환
}
}
public class MyStack_01 {
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println(stack.peek()); // C
System.out.println(stack.pop()); // C
System.out.println(stack.pop()); // B
System.out.println(stack.pop()); // A
System.out.println(stack.pop());
}
}
3) arrayList & linkedList
- 둘 중에 arrayList가 Stack에 더 좋다
4) 실습 2
import java.util.Stack;
class Coin {
private int value;
public Coin (int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public class MyStack_02 {
public static void main(String[] args) {
Stack<Coin> coinBox = new Stack<>();
coinBox.push(new Coin(100));
coinBox.push(new Coin(50));
coinBox.push(new Coin(500));
coinBox.push(new Coin(10));
while (!coinBox.isEmpty()) {
Coin coin = coinBox.pop();
System.out.println("꺼내온 동전 : " + coin.getValue() + "원");
}
/*
꺼내온 동전 : 10원
꺼내온 동전 : 500원
꺼내온 동전 : 50원
꺼내온 동전 : 100원
*/
}
}
5) 참고 사항
- 체인 메서드 : coinBox.pop().getValue() 메서드 연결하여 사용. 앞부터 순서대로 메서드 실행
1) Queue
- FIFO 자료구조에서 사용되는 메서드 정의
- 선입선출 : 먼저 들어온 것이 먼저 나간다
리턴 타입 | 메소드 | 설명 |
boolean | offer(E e) | 주어진 개체를 넣음 |
E | peek() | 객체를 가져옴. 제거 X |
E | poll() | 객체를 가져옴. 제거 O |
2) 실습
import java.util.LinkedList;
class MyQueue {
private LinkedList<String> linkedList = new LinkedList<>();
public void enQueue(String data) {
linkedList.add(data);
}
public String deQueue() {
int len = linkedList.size();
if (len == 0) {
System.out.println("큐가 비었습니다.");
return null;
}
return (linkedList.remove(0)); // 맨 앞의 자료 반환하고 배열에서 제거
}
}
public class MyQueue_01 {
public static void main(String[] args){
MyQueue queue = new MyQueue();
queue.enQueue("A");
queue.enQueue("B");
queue.enQueue("C");
System.out.println(queue.deQueue()); // A
System.out.println(queue.deQueue()); // B
System.out.println(queue.deQueue()); // C
}
}
3) 실습2
import java.util.LinkedList;
import java.util.Queue;
class Message {
public String command;
public String to;
public Message(String command, String to) {
this.command = command;
this.to = to;
}
}
public class MyQueue_02 {
public static void main(String[] args) {
Queue<Message> messageQueue = new LinkedList<>();
// 메시지 저장
messageQueue.offer(new Message("sendMail", "홍길동"));
messageQueue.offer(new Message("sendSMS", "박성훈"));
messageQueue.offer(new Message("sendKakaotalk", "홍두께"));
while (!messageQueue.isEmpty()) {
Message message = messageQueue.poll();
switch (message.command) {
case "sendMail":
System.out.println(message.to + "님에게 메일을 보냈습니다.");
break;
case "sendSMS":
System.out.println(message.to + "님에게 SMS를 보냈습니다.");
break;
case "sendKakaotalk":
System.out.println(message.to + "님에게 카카오톡을 보냈습니다.");
break;
}
}
}
}
1) Set 컬렉션 : 중복되지 않게 자료를 관리
- 순서 상관없이, 중복 제거 저장
기능 | 메소드 | 설명 |
객체 추가 | boolean add(E e) | 주어진 객체 저장. 객체가 저장되면 true를 리턴, 중복이면 false 리턴 |
객체 검색 | boolean contains(Object o) | 주어진 객체가 저장된 지 조사 |
boolean isEmpty() | 컬렉션이 비어있는 지 조사 | |
Iterator<E> iterator() | 저장 객체를 한 번씩 가져오는 반복자 리턴 | |
객체 삭제 | void clear() | 저장된 모든 객체 삭제 |
boolean remove(Object o) | 주어진 객체를 삭제 |
2) HsheSet : Set 인터페이스 구현 클래스, 객체를들을 순서 없이 저장, 동일 객체 중복 저장 X
import java.util.HashSet;
public class MyHashSet {
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<>();
hashSet.add("임정순");
hashSet.add("박현정");
hashSet.add("홍연의");
hashSet.add("강감찬");
hashSet.add("강감찬");
// 중복된 문자열은 제거되고 출력 순서와 입력 순서는 상관없음
System.out.println(hashSet);
}
}
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class MyHashSet_02 {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("JAVA");
set.add("JDBC");
set.add("Servlet/JSP");
set.add("JAVA"); // JAVA는 한 번만 저장됨.
set.add("iBATIS");
int size = set.size(); // 저장된 객체 수 얻기
System.out.println("총 객체수: " + size); // 총 객체수 : 4
System.out.println("foreach 문으로 출력 시작");
for (String s : set) {
System.out.println("\t" + s);
}
System.out.println();
Iterator<String> iterator = set.iterator(); // 반복자 얻기
while (iterator.hasNext()) { // 객체 수만큼 루핑
String element = iterator.next(); // 1개의 객체를 가져옴.
System.out.println("\t" + element);
}
set.remove("JDBC"); // 1개의 객체 삭제
set.remove("iBATIS"); // 1개의 객체 삭제
System.out.println("총 객체수: " + set.size());
System.out.println("foreach 문으로 출력 시작");
for (String s : set) {
System.out.println("\t" + s);
}
System.out.println();
set.clear(); // 모든 객체를 제거하고 비움.
if(set.isEmpty()) {
System.out.println("비어 있음");
}
}
}
'Dev > Java' 카테고리의 다른 글
JAVA JDBC (deposit, updateBalance, withdraw, selectOne, inquire, disConnect, accountDAO) (0) | 2024.02.19 |
---|---|
[코리아IT아카데미] JAVA - Exception (예외) (0) | 2024.02.02 |
[코리아IT아카데미] Java - List, TreeSet, Map, Compare (0) | 2024.01.29 |
[코리아IT아카데미] Java - Interface (2) | 2024.01.25 |