[JAVA] 17. 제네릭 & Wrapper & 컬렉션 & 오브젝트 Ⅴ. Collection

최재원's avatar
Feb 20, 2025
[JAVA] 17. 제네릭 & Wrapper & 컬렉션 & 오브젝트 Ⅴ. Collection
  • Set : 중복된 원소를 가지지 않는 집합을 나타내는 구조
  • List : 순서가 있는 자료구조
    • ArrayList
    • LinkedList

특징

  • 컬렉션은 제네릭을 사용
  • 랩퍼클래스만 사용

1. ArrayList

ArrayList<Type> list = new ArrayList();
package ex17; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayList01 { public static void main(String[] args) { ArrayList list = new ArrayList(); // ArrayList에 추가하기 list.add("a"); list.add(123); list.add(true); System.out.println(list); // ArrayList에 삽입하기 list.add(1, "b"); list.add(2, 0); System.out.println(list); // ArrayList에 데이터 수정하기 list.set(0, "xyz"); System.out.println(list); // ArrayList에 데이터 삭제하기 list.remove(0); System.out.println(list); // ArrayList에 데이터 읽기 System.out.println(list.get(0)); // ArrayList에 크기 읽기 System.out.println(list.size()); // 배열을 리스트로 변경 List list2 = Arrays.asList(new String[5]); System.out.println(list2); } }

실습

package ex17; import java.util.ArrayList; class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "(" + x + ", " + y + ")"; } } public class ArrayListTest { public static void main(String[] args) { ArrayList<Point> list = new ArrayList(); list.add(new Point(0, 0)); list.add(new Point(4, 0)); list.add(new Point(3, 5)); list.add(new Point(-1, 3)); list.add(new Point(13, 2)); System.out.println(list); } }
notion image
package ex17; import java.util.ArrayList; public class ArrayListTest2 { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Mango"); list.add("Pear"); list.add("Grape"); int index = list.indexOf("Mango"); // 저장된 문자열을 풀스캔으로 검색 System.out.println("Mango의 위치: " + index); } }
notion image

2. LinkedList

연속된 데이터의 중간에서 삽입과 삭제가 빈번히 일어나는 경우에 좋다.
데이터가 이동하는 것이 아닌 연결을 하기 때문.
package ex17; import java.util.LinkedList; public class LinkedList01 { public static void main(String[] args) { LinkedList list = new LinkedList(); // LinkedList에 데이터 추가 list.addFirst(123); list.add("Hello"); list.add(2, "bye"); list.addLast(34); System.out.println(list); // LinkedList 데이터 읽기 list.get(0); list.getFirst(); list.peek(); list.getLast(); // LinkedList 데이터 변경 list.set(0, 1234); System.out.println(list); // LinkedList 데이터 삭제 list.remove(); list.remove(1); System.out.println(list); // LinkedList 크기 확인 System.out.println(list.size()); } }

실습

package ex17; import java.util.LinkedList; public class LinkedListTest { public static void main(String[] args) { LinkedList<String> list = new LinkedList(); list.add("MILK"); list.add("BREAD"); list.add("BUTTER"); list.add(1, "APPLE"); list.set(2, "GRAPE"); list.remove(3); for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i) + " "); } } }
notion image
리스트의 앞 부분에 원소를 추가하거나 삭제하는 일이 빈번하다면 LinkedList가 낫다.
일반적으로는 ArrayList가 더 낫다

3. Set

순서에 상관없이 데이터만 저장하고 싶을 때 사용
package ex17; import java.util.HashSet; public class HashSet01 { public static void main(String[] args) { HashSet set = new HashSet(); // HashSet에 데이터 추가하기 set.add(1); set.add("a"); set.add(true); // HashSet에 데이터 삭제하기 set.remove(true); set.clear(); // HashSet의 크기 확인하기 System.out.println(set.size()); } }

실습

package ex17; import java.util.HashSet; public class SetTest { public static void main(String[] args) { HashSet<String> set = new HashSet<String>(); set.add("Mike"); set.add("Bread"); set.add("Butter"); set.add("Cheese"); set.add("Ham"); set.add("Ham"); System.out.println(set); if (set.contains("Ham")) { System.out.println("Ham도 포함되어 있음"); } } }
notion image
package ex17; import java.util.HashSet; import java.util.LinkedHashSet; public class SetTest { public static void main(String[] args) { HashSet<String> set = new LinkedHashSet<String>(); set.add("Mike"); set.add("Bread"); set.add("Butter"); set.add("Cheese"); set.add("Ham"); set.add("Ham"); System.out.println(set); if (set.contains("Ham")) { System.out.println("Ham도 포함되어 있음"); } } }
notion image
  • LinkedHashSet = 입력된 순서대로 정렬
package ex17; import java.util.TreeSet; public class SetTest { public static void main(String[] args) { TreeSet<String> set = new TreeSet<>(); set.add("Mike"); set.add("Bread"); set.add("Butter"); set.add("Cheese"); set.add("Ham"); set.add("Ham"); System.out.println(set); if (set.contains("Ham")) { System.out.println("Ham도 포함되어 있음"); } } }
notion image
  • TreeSet = 오름차순 정렬
package ex17; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class SetTest { public static void main(String[] args) { Set s1 = new HashSet(Arrays.asList(1, 2, 3, 4, 5, 6)); Set s2 = new HashSet(Arrays.asList(3, 4, 5)); s1.retainAll(s2); System.out.println(s1); } }
notion image
  • 두 집합에 retainAll() 메서드를 사용해 교집합을 만들 수 있다.
package ex17; import java.util.HashSet; import java.util.Set; public class FindDuplication { public static void main(String[] args) { Set<String> s = new HashSet(); String[] sample = {"사과", "사과", "바나나", "토마토"}; for (String a : sample) { if (!s.add(a)) { // 집합에 추가되지 않으면 중복단어이다. System.out.println("중복된 단어: " + a); } } System.out.println(s.size() + " 중복되지 않은 단어: " + s); } }
notion image

4. Map

키-값을 쌍으로 묶어서 저장하는 자료구조
키(key)
값(value)
“kim”
“1234”
“park”
“pass”
package ex17; import java.util.HashMap; import java.util.Map; public class HashMap01 { public static void main(String[] args) { Map<String, Integer> map = new HashMap(); // HashMap 데이터 초기화 Map<String, Integer> map2 = Map.of("c", 1, "d", 2, "e", 3); // HashMap 데이터 추가 map.put("a", 1); map.put("b", 2); // HashMap 데이터 읽기 System.out.println(map.get("a")); // HashMap 데이터 삭제 map.remove("a"); // HashMap 데이터 확인 map.containsKey("a"); // "a" 키가 있는지 확인 // HashMap 데이터 업데이트 map.replace("a", 123); } }

실습

package ex17; import java.util.HashMap; import java.util.Map; public class MapTest { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("kim", "1234"); map.put("park", "pass"); map.put("lee", "word"); System.out.println(map.get("lee")); System.out.println(map.keySet()); for (String key : map.keySet()) { String value = map.get(key); System.out.println("key= " + key + " value= " + value); } map.remove(1); map.put("choi", "password"); System.out.println(map); } }
notion image

5. Queue

데이터를 처리하기 전에 잠시 저장하는 자료구조
FIFO(first - in - first - out)
package ex17; import java.util.LinkedList; import java.util.Queue; public class Queue01 { public static void main(String[] args) { Queue q = new LinkedList(); // Queue 데이터 추가하기 q.add(1); q.add("a"); q.add(true); // Queue 데이터 삭제하기 q.remove(); q.poll(); q.peek(); // 삭제하지 않고 가져옴 // Queue 데이터 크기 확인 System.out.println(q.size()); } }

실습

package ex17; import java.util.LinkedList; import java.util.Queue; public class QueueTest { public static void main(String[] args) { Queue<Integer> q = new LinkedList(); for (int i = 0; i < 5; i++) { q.add(i); } System.out.println("큐의 요소: " + q); int e = q.remove(); System.out.println("삭제된 요소: " + e); System.out.println(q); } }
notion image
package ex17; import java.util.PriorityQueue; public class PriorityQueueTest { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.add(100); pq.add(1); pq.add(10); System.out.println(pq); System.out.println("삭제된 원소: " + pq.remove()); } }
notion image
  • 우선순위 큐 가장 작은 값을 먼저 사용한다.

6. Collections 클래스

  • 정렬(Sorting)
    • 합병 정렬(Merge sort)
  • 섞기(Shuffling)
  • 탐색(Searching)

정렬

package ex17; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Collections01 { public static void main(String[] args) { List<String> list = new LinkedList<String>(); list.add("mango"); list.add("banana"); list.add("apple"); Collections.sort(list); System.out.println(list); } }
notion image

실습

package ex17; import java.util.*; public class Sort { public static void main(String[] args) { String[] sample = {"i", "walk", "the", "line"}; List<String> list = Arrays.asList(sample); Collections.sort(list); System.out.println(list); } }
notion image
package ex17; import java.util.Arrays; import java.util.Collections; import java.util.List; class StudentSort implements Comparable<StudentSort> { int number; String name; public StudentSort(int number, String name) { this.number = number; this.name = name; } @Override public String toString() { return name; } @Override public int compareTo(StudentSort s) { return this.number - s.number; // 음수면 오름차순, 양수면 내림차순 } } public class SortTest { public static void main(String[] args) { StudentSort[] array = { new StudentSort(2, "김철수"), new StudentSort(3, "이철수"), new StudentSort(1, "박철수"), }; List<StudentSort> list = Arrays.asList(array); Collections.sort(list); System.out.println(list); } }
notion image
  • 사용자가 만든 객체는 Comparable 인터페이스가 구현되어 있지 않아 Collections.sort()를 사용할 수 없다.
  • Collections.sort() 메서드를 사용하고 싶다면 클래스를 Comparable로 구현해야하고 compareTo() 메서드를 오버라이드 해야한다.

섞기

package ex17; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Shuffle { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list.add(i); } Collections.shuffle(list); System.out.println(list); } }
notion image

탐색

package ex17; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Search { public static void main(String[] args) { int key = 50; List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { list.add(i); } int index = Collections.binarySearch(list, key); System.out.println("탐색의 반환값 = " + index); } }
notion image

최종 연습 카드 게임

package ex17; import java.util.ArrayList; class Card { // Spades, Clubs, Diamonds, Hearts 종류의 suit String suit; // 2, 3, 4, 5, 6, 7, 8, 9, 10, J(잭), Q(퀸), K(킹), A(에이스) String number; public Card(String suit, String number) { this.suit = suit; this.number = number; } @Override public String toString() { return "Card{" + "suit='" + suit + '\'' + ", number='" + number + '\'' + '}'; } } class Deck { private ArrayList<Card> deck; private String[] suit; private String[] number; public Deck(String[] suit, String[] number) { for (String s : suit) { for (String n : number) { Card c = new Card(s, n); deck.add(c); } } } public void shuffle() { } public Card deal() { return null; } } class Player { ArrayList<Card> list; public void getCard(Card card) { list.add(card); } public void showCards() { System.out.println(list); } } public class CardGame { public static void main(String[] args) { } }
Share article

jjack1