개발/java

자바에서 자주 사용되는 자료구조와 자료형 간단 정리

바이솔 2024. 7. 15. 13:35

자바 코딩 테스트에서 자주 사용되는 자료구조와 자료형에 대해 정리했습니다. 각 자료구조와 자료형별로 기본적인 사용법과 메소드들

1. 자료구조

1.1 스택 (Stack)

스택은 LIFO(Last In First Out) 구조로, 마지막에 삽입된 데이터가 가장 먼저 삭제됨.

선언:

Stack<Integer> stack = new Stack<>();

메소드:

push(): top에 삽입

stack.push(1);

pop(): top을 삭제 & 확인

int top = stack.pop();

peek(): top을 확인

int top = stack.peek();

1.2 큐 (Queue)

큐는 FIFO(First In First Out) 구조로, 처음 삽입된 데이터가 가장 먼저 삭제됨.

Queue<Integer> queue = new LinkedList<>();

add(): rear에 삽입

queue.add(1);

poll(): front를 삭제 & 확인

int front = queue.poll();

peek(): front를 확인

int front = queue.peek();

1.3 우선순위 큐 (PriorityQueue)

우선순위 큐는 요소가 우선순위에 따라 처리되는 큐.

PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(1);
int topPriority = pq.remove();

2.1 ArrayList

ArrayList는 가변 길이 배열을 구현한 클래스

ArrayList<Integer> list = new ArrayList<>();
list.add(1);
int size = list.size();
Collections.sort(list);
int index = list.indexOf(3);

 

2.2 HashSet

HashSet은 중복된 요소를 허용하지 않는 집합

HashSet<String> set = new HashSet<>();
set.add("a");

2.3 HashMap

HashMap은 키-값 쌍을 저장하는 자료구

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "value");
String value = map.get(1);