Java 문법 2주차 2-14,15,16 컬렉션
2-14 컬렉션
Java 에서 컬렉션 은 배열보다 다수의 참조형 데이터를 더 쉽고 효과적으로 처리할 수 있는 기능을 많이 가지고 있다
컬렉션 기능 : 크기 자동조정/ 추가/ 수정/ 삭제/ 반복/ 순회/ 필터/ 포함확인 등….
컬렉션 종류
Collection 에는 List, Set , Queue , Map 이 있다.
-
List : 순서가 있는 데이터의 집합 (데이터 중복 허용) - 배열과 비슷
Queue : 빨대처럼 한쪽에서 데이터를 넣고 반대쪽에서 데이터를 뺄 수 있는 집합
- First In First Out(FIFO) : 먼저들어간 순서대로 값을 조회할 수 있다.
<-> Stack은 First in Last Out(FILO)
Set : 순서가 없는 데이터의 집합 (데이터 중복 허용 안함) - 순서없고 중복없는 배열
Map : 순서가 없는 (Key(유니크함),Value) 쌍으로 이루어진 데이터의 집합 (Key값 중복 허용 안함)
-
2-15 List
ArrayList
package week02.collection;
import java.util.ArrayList;
public class Col1 {
public static void main(String[] args) {
// List
// 순서가 있는 데이터의 집합 => Array(최초 길이를 알아야(설정해줘야) 함)
// 처음의 길이를 몰라도 만들 수 있음
// 1) Array -> 정적배열
// 2) List(ArrayList) -> 동적배열(크기가 가변적으로 늘어난다)
// - 생성 시점에 작은 연속된 공간을 요청해서 참조형 변수들을 담아놓는다.
// - 값이 추가될 때 더 큰 공간이 필요하면 더 큰 공간을 받아서 저장하니깐 상관없다.
ArrayList<Integer> intList = new ArrayList<Integer>(); //선언 + 생성
intList.add(99);
intList.add(15);
intList.add(3);
System.out.println(intList.get(1)); // 15
// 2번째 있는 값(15)을 바꿔보자.
intList.set(1, 10);
System.out.println(intList.get(1)); // 15- > 10
// 삭제
intList.remove(0);
System.out.println(intList.get(0)); // 10. 0번째의 99가 삭제되고 1번째 10가 0번째가됨.
System.out.println("클리어 전");
System.out.println(intList.toString()); // [10, 3]
intList.clear();
System.out.println("클리어 후");
System.out.println(intList.toString()); // []
}
}
linkedList
LinkedList는 메모리에 남는 공간을 요청해서 여기 저기 나누어서 실제 값을 담아 놓는다.
package week02.collection;
import java.util.LinkedList;
public class Col2 {
public static void main(String[] args) {
// linked list
// 메모리에 남는 공간을 요청해서 여기 저기 나누어서 실제 값을 담아놓는다.
// 실제 값이 있는 주소값으로 목록을 구성하고 저장하는 자료구조.
// 기본적 기능은 -> ArrayList와 동일!
// LinkedList는 값 -> 여기 저기 나누어서 : 조회하는 속도가 "느리다"
// 대신 값을 추가하거나, 삭제할 때는 빠르다.
LinkedList<Integer> linkedList = new LinkedList<Integer>();
linkedList.add(5);
linkedList.add(10);
linkedList.add(3);
System.out.println(linkedList.get(0)); // 5
System.out.println(linkedList.get(1)); // 10
System.out.println(linkedList.get(2)); // 3
System.out.println(linkedList.toString()); // 조회할 때는 arraylist보다 느리다.
// [5, 10, 3]
linkedList.add(200);
System.out.println(linkedList.toString()); // [5, 10, 3, 200]
linkedList.add(2, 4); // linkedList는 이렇게 바로 추가가능
System.out.println(linkedList.toString()); // 3(index 2의 자리)-> 4
// [5, 10, 4, 3, 200]
linkedList.set(1, 30); // 10(index 1의 자리) -> 30
System.out.println(linkedList.toString()); // [5, 30, 4, 3, 200]
linkedList.remove(1); // index 1의 자리를 지움
System.out.println(linkedList.toString()); // [5, 4, 3, 200]
linkedList.clear();
System.out.println(linkedList.toString()); // []
}
}
2-16
Stack
FILO(first in last out), 바스켓구조
기능
- push() : 삽입
- peek() : 조회
- pop() : Stack의 마지막 index 자리의 값을 삭제와 동시에 조회
package week02.collection;
import java.util.Stack;
public class Col3 {
public static void main(String[] args) {
// Stack
// 수직으로 값을 쌓아놓고, 넣었다가 뺀다. FILO(First In Last Out : 바스켓)
// push, peek, pop
// 최근 저장된 데이터를 나열하고 싶거나, 데이터의 중복 처리를 막고 싶을 때 사용
Stack<Integer> intStack = new Stack<Integer>(); // 선언 및 생성
intStack.push(10);
intStack.push(15);
intStack.push(1);
// 다 지워질 때 까지 출력
while(!intStack.isEmpty()) { // isEmpty는 값이 없을 때. 원래는 false 값이지만
// !를 앞에 붙임으로써 반대인 True, 값이 있을 때로 바꿈
System.out.println(intStack.pop()); // pop은 바스켓에서 맨 윗것만 빼내면서 출력
// --- 현재까지 코드해석 ---
// intStack에 10, 15, 1을 넣었는데.
// intStack에 값이 남아있는 동안
// intStack에서 마지막 값을 빼내면서 출력.
// 출력 -> 1 15 10
}
// 다시 추가
intStack.push(10);
intStack.push(15);
intStack.push(1);
// peak
System.out.println(intStack.peek()); // 마지막 값을 골라 출력 (빼내지 않음)
// size
System.out.println(intStack.size()); // intStack의 크기 -> 3
}
}
Queue
FIFO(First In First Out), 빨대형 구조
기능
add() : 추가
peek() : 조회
poll() : Queue의 맨 처음 index 자리의 값을 삭제와 동시에 조회
package week02.collection;
import java.util.LinkedList;
import java.util.Queue;
public class Col4 {
public static void main(String[] args) {
// Queue : FIFO(First In First Out)
// add, peek, poll
// 생성자가 없는 인터페이스 <-
Queue<Integer> intQueue = new LinkedList<>(); // queue를 선언, 생성
intQueue.add(1);
intQueue.add(5);
intQueue.add(9);
while(!intQueue.isEmpty()) { // !을 이용하여 반대로 intQueue에 값이 있을때
System.out.println(intQueue.poll()); // 처음에 add된게 처음에 빠지면서 출력
// 1 5 9
}
// 추가
intQueue.add(1);
intQueue.add(5);
intQueue.add(9);
// peak
System.out.println(intQueue.peek()); // 맨 먼저넣은게 조회됨. 1
System.out.println(intQueue.size()); // 크기 3
}
}
Set
집합. 순서X 중복X
기능
- add() : 추가
- get() : 조회
- remove() : 삭제
- contains() : 값 포함여부 확인
Set 종류
- HashSet : 가장 빠르고 예측 불가
- TreeSet : 정렬된 순서대로 보관하고 정렬방법을 지정할 수 있습니다.
- LinkedHashSet : 추가된 순서, 또는 가장 최근에 접근한 순서대로 접근이 가능합니다.
package week02.collection;
import com.sun.jdi.IntegerValue;
import java.util.HashSet;
import java.util.Set;
public class Col5 {
public static void main(String[] args) {
// Set(집합) : 순서 없고, 중복 없음
// 순서가 보장되지 않는 대신 중복을 허용하지 않도록 하는 프로그램에서 사용할 수 있는 자료구조
// Set -> 그냥 쓸 수도 있음. 그러나, HashSet, TreeSet 등으로 응용해서 같이 사용 가능
// Set은 생성자가 없는 껍데기라서 바로 생성할 수 없음 -> 3주차
// 생성자가 존재하는 HashSet을 이용해서 -> Set을 구현해 볼 수 있다.
Set<Integer> intSet = new HashSet<>(); // 선언 및 생성
intSet.add(1);
intSet.add(12);
intSet.add(5);
intSet.add(9);
intSet.add(1);
intSet.add(12);
for (Integer value: intSet) { // value라는 변수명에 intSet이 돌면서 for문 실행
System.out.println(value); // 1 5 9 12. 집합의 개념이라 순서없이 중복 없음.
}
// contains 포함되어있는지?
System.out.println(intSet.contains(2)); // 없음. false
System.out.println(intSet.contains(5)); // 5있음. true
// remove들은 다른 것들과 똑같기 때문에 skip
}
}
Map
key - value pair 구조
기능
- put(key값, value값) : 추가
- get(key값) : 조회
- remove(key값) : 삭제
- keySet() : 전체 key값 조회
- values() : 전체 value값 조회
종류
- HashMap : 중복을 허용하지 않고 순서를 보장하지 않으며, key값으로 null을 허용합니다.
- TreeMap : key 값을 기준으로 정렬이 가능하지만, 저장시간이 다소 오래걸립니다.
package week02.collection;
import java.util.HashMap;
import java.util.Map;
public class Col6 {
public static void main(String[] args) {
// Map : key - value pair -> 중요!
// key라는 값으로 unique하게 보장이 돼야 함!
// Map -> HashMap, TreeMap으로 응용!
Map<String, Integer> intMap = new HashMap<>(); // key = String, value: Integer
// 키 값
intMap.put("일", 11);
intMap.put("이", 12);
intMap.put("삼", 13);
intMap.put("삼", 14); // 중복 key
intMap.put("삼", 15); // 중복 key
// key 값 전체 출력(향상된 for문)
for (String key: intMap.keySet()) {
System.out.println(key); // 중복된 key는 생략해버림. 일 이 삼
}
// value 값 전체 출력(향상된 for문)
for (Integer value: intMap.values()) {
System.out.println(value); // 중복된 value중 마지막 값으로 덮어씀. 12 11 15
}
System.out.println(intMap.get("삼")); // key"삼"의 value값인 15 출력
}
}