Java

[Java Programming] 11.2 컬렉션 (ListArray, Map, HashMap, set)

코딩펭귄 2024. 2. 1. 01:04

컬렉션 프레임워크(Collection Framework)

Java에서 흔하게 사용되는 여러 자료구조들을 제네릭을 이용해 미리 작성해 놓은 툴

인터페이스와 구현클래스의 종류 

1. List (Interface)

ArrayList (Implemented class)

- (set과 다르게) 중복값을 가질 수 있음

- 배열을 편하게 사용하기 위한 자료구조

- 앞서 만든 ScoreList와 유사

 

2. Map (Interface)

HashMap (Implemented class)

- 데이터를 key, value 페어로 가지고 다닐 수 있게 함

- 하나의 데이터가 Key:Value 쌍으로 이루어진 자료구조

- Map<k, v > -> k(key)값에는 : 문자열(String), 정수(int)를 가장 많이 씀 (+enum)

 

3. Set (Interface)

HashSet (Implemented class)

- 집합 처리시 사용

- ArrayList와 유사하지만, 중복값을 가지지 못하는 자료구조 ( 집합이다 보니 중복된 데이터를 다룰 수 없다 )

- 잘 사용하지 않음


List & ArrayList

- List<E>는 인터페이스이기 때문에 객체를 스스로 생성할 수 없음

  -> 객체를 생성하기 위해서는 List<E>를 상속받아 자식클래스를 생성한 후

    -> 생성한 자식클래스를 이용해 객체를 생성

ex) List<E>인터페이스를 구현한 대표적인 클래스 : ArrayList<E>, Vector<E>, LinkedList<E>

- List 인터페이스를 구현한 ArrayList- 배열 대신 사용

 

List인스턴스 만드는  방법 

List<Integer> scoreList = new ArrayList<>();   

-->  isA관계가 성립하기떄문에 이렇게 작성 가능 

-> 이형태는 변경가능하지만, List of는 변경불가능함

List Interface

public interface List<E> extends Collection<E>

ArrayList Class

public class ArrayList<E> extends AbstractList<E>

        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

List Interface의 주요 메소드

리스트는 값을 add 하면 무조건 다 true

List<E>의 다양한 메소드

  리턴타입 메서드명 기능
  boolean add(E element) 매개변수로 입력된 원소를 리스트 마지막에 추가
  void add(int index, E element) index위치에 입력된 원소 추가
데이터추가 boolean addAll(Collection<? Extends E> c 매개변수로 입력된 컬렉션 전체를 마지막에 추가
  boolean addAll(int index, Collection<? Extends E> c) index위치에 입력된 컬렉션 전체 추가
데이터변경 E set(int index, E element) index위치의 원솟값을 입력된 원소로 변경
  E remove(int index) index위치의 원솟값 삭제
데이터삭제 boolean remove(Object o) 원소 중 매개변수 입력과 동일한 객체 삭제
  void clear() 전체 원소 삭제
리스트데이터정보추출 E get(int index) index위치의 원솟값 꺼내 리턴
  int size() 리스트 객체 내에 포함된 원소의 개수
  boolean isEmpty() 리스트의 원소가 하나도 없는지 여부 리턴
리스트배열 반환 Object[] toArray() 리스트를 Object배열로 변환
  T[] toArray(T[]t) 입력매개변수로 전달할 타입의 배열로 변환
List 사용 실습
package generic_collection;

import java.util.List;
import java.util.ArrayList;

public class ListCollectionTest {

	public static void main(String[] args) {
		List<Integer> scoreList = new ArrayList<>();
		//1.List에 데이터 추가
		scoreList.add(100);
		scoreList.add(90);
		scoreList.add(80);
		scoreList.add(70);
		scoreList.add(60);
		System.out.println(scoreList); //[100, 90, 80, 70, 60]
		System.out.println(scoreList.size()); //5
		
		//2.List 데이터 조회 - 데이터가져오기 : get
		int score = scoreList.get(0);
		System.out.println(score); //100
		score = scoreList.get(1);
		System.out.println(score);	//90	
		score = scoreList.get(2);
		System.out.println(score);	//80
		score = scoreList.get(3);
		System.out.println(score);  //70
		score = scoreList.get(4);
		System.out.println(score); //60
		
//		score = scoreList.get(5); 
//		System.out.println(score);	//IndexOutOfBoundsException
		
		//3.List 반복데이터 조회
		for (int i = 0; i<scoreList.size(); i++) {
			score = scoreList.get(i);
			System.out.println(score);  // 2번 출력결과와 동일. 2번코드를 짧게한것
		}
		
		//4. List 데이터 삭제
		//ArrayList의 remove특징 : 3번인덱스가 지워지만, 인덱스4가 3으로 바뀜.
		// 인덱스5는 4, 인덱스6은 5로 바뀜 (= 인덱스가 하나씩 땡겨짐)
		scoreList.remove(3);
		System.out.println(scoreList); // [100, 90, 80, 60]
		System.out.println(scoreList.size()); // 4
		
		//5. List 데이터 모두삭제 - scoreList 전부다 지움. = 있던 데이터 전부 날려라
		scoreList.clear();
		System.out.println(scoreList); //[]
		System.out.println(scoreList.size()); //0
		
		//6. List가 비어있는지 확인
		System.out.println(scoreList.isEmpty()); //비어있으므로 true
		System.out.println(scoreList);  //[]
		System.out.println(scoreList.size()); //0
		
		//7.값 존재여부 확인
		if ( ! scoreList.contains(90) ) { //scoreList에 90이 없다면 값을 넣어라
			scoreList.add(90); // 비어있는 리스트상태이므로, 90이 없으므로 실행됨
		}
		System.out.println(scoreList);  //[90]
		System.out.println(scoreList.size()); //1
		
		//8.리스트 복사
		System.out.println(System.identityHashCode(scoreList)); //664740647
		System.out.println(scoreList);  //[90]
		System.out.println(scoreList.size()); //1
		
		List<Integer> scoreList2 = new ArrayList<>();
		scoreList2.addAll(scoreList);
		System.out.println(System.identityHashCode(scoreList2)); //804564176
		System.out.println(scoreList2);  //[90]
		System.out.println(scoreList2.size()); //1
	}
}

 


Map & HashMap

- Map 인터페이스를 구현한 HashMap

- 데이터를 :값 쌍(Entry) 으로 관리할 때 사용

- Map&HashMap : 컬렉션 프레임워크지만, 컬렉션과는 관련 없음(리스트, set만이 collection줄수있음)

 

Map 인스턴스 만드는 방법

Map<String, Integer> priceMap = new HashMap<>();

Map Interface

public interface Map<K, V>

HashMap Class

public class HashMap<K,V> extends AbstractMap<K,V>

    implements Map<K,V>, Cloneable, Serializable

 

Map Interface의 주요 메소드들

- 리스트와 비슷하지만 다른점 : 데이터 넣을때 put -> 반환타입 : V (=value)
- get의 파라미터가 object로 들어감 (list는 index이므로 int)
- List출력 : [ ]  /  map출력 : { }

 

Map 사용 실습
package generic_collection;

import java.util.HashMap;
import java.util.Map;

public class MapCollectionTest {

	public static void main(String[] args) {
		Map<String, Integer> priceMap = new HashMap<>();
		//1. Map에 데이터 추가
		// MAP에는 모든 reference type(ex, string, list 등) 넣을 수 있음
		priceMap.put("Apple Macbook Pro", 3_500_000);
		priceMap.put("SamSung Galaxy Book", 1_500_000);
		priceMap.put("LG Gram", 1_700_000);
		// Put의 의미 : 없으면 만들고, 있으면 수정해라
		// -> 같은키를 가지고 다른 value값 넣어주면, LG Gram에대한 Value값만이 수정됨
	
		System.out.println(priceMap); //{LG Gram=1700000, SamSung Galaxy Book=1500000, Apple Macbook Pro=3500000}
		System.out.println(priceMap.size()); //3

		priceMap.put("LG Gram", 1_800_000);
		System.out.println(priceMap); // {LG Gram=1800000, SamSung Galaxy Book=1500000, Apple Macbook Pro=3500000}
		System.out.println(priceMap.size()); //3
		
		//2. Map 데이터 조회
		int applePrice = priceMap.get("Apple Macbook Pro");
		System.out.println(applePrice);
//		applePrice = priceMap.get("apple macbook pro");
//		System.out.println(applePrice); //NullPointerException
		
		//3. Map 데이터 삭제
		priceMap.remove("Apple Macbook Pro"); //지울땐 remove로 키값으로접근
		System.out.println(priceMap); //{LG Gram=1800000, SamSung Galaxy Book=1500000}
		System.out.println(priceMap.size()); //2
		
		
		//4. Map데이터 모두삭제
		priceMap.clear();
		System.out.println(priceMap); //{}
		System.out.println(priceMap.size()); //0		
		
		
		//5. Map비어있는지 확인
		boolean isEmpty = priceMap.isEmpty();
		//isEmpty체크시 반드시 그 전에 null체크부터 해주기
		System.out.println(isEmpty); //true
		System.out.println(priceMap); //{} 
		System.out.println(priceMap.size()); //0
		
		
		//6. Map에 동일한 Key가 있는지 확인
		priceMap.put("Apple Macbook Pro", 3_500_000);
		priceMap.put("SamSung Galaxy Book", 1_500_000);
		priceMap.put("LG Gram", 1_700_000);
		if ( !priceMap.containsKey("LG Gram")) { //키값이 없다면 아래 코드 실행
			priceMap.put("LG Gram", 1_600_000);
		}
		System.out.println(priceMap); // {LG Gram=1700000, SamSung Galaxy Book=1500000, Apple Macbook Pro=3500000}
		System.out.println(priceMap.size()); // 3
			
		
		//7. Map에 동일한 value가 있는지 확인
		//사실, key가 중복이 안되는것이지, value중복은 흔함. containsValue()는 잘 안씀
		if ( priceMap.containsValue(1_700_000)) {
			priceMap.put("LG Gram", 1_600_000);
		}
		System.out.println(priceMap); // {LG Gram=1600000, SamSung Galaxy Book=1500000, Apple Macbook Pro=3500000}

		System.out.println(priceMap.size()); // 3
		
		//8. Map 복사
		Map<String, Integer> priceMap2 = new HashMap<>();
		priceMap2.putAll(priceMap2);
		
		System.out.println(System.identityHashCode(priceMap));
		System.out.println(priceMap);
		System.out.println(priceMap.size());
		
		System.out.println(System.identityHashCode(priceMap2));
		System.out.println(priceMap2);
		System.out.println(priceMap2.size());

		/* 664740647
		  {LG Gram=1600000, SamSung Galaxy Book=1500000, Apple Macbook Pro=3500000}
		  3
		  804564176
		  {}
		  0
		 */
	}
}

 


 

Set & HashSet

- Set 인터페이스를 구현한 HashSet
- Set : 리스트와 거의 동일 (collectio을 상속받는 인터페이스라는 점에서 동일)
- Set : ArrayList와 달리 '중복된 데이터'를 넣을수 없다 : add() 반복해도 한번만 됨

 

set인스턴스 만드는 방법

Set<Integer> numbers = new HashSet<>();

Set Interface

public interface Set<E> extends Collection<E>

HashSetClass

public class HashSet<E>

    extends AbstractSet<E>

    implements Set<E>, Cloneable, java.io.Serializable

 
주요 메소드
- 리스트와 달리 get이 없으므로 가져올 수 있는 메소드가 없음. 오로지 출력해서 값 확인하는 방법밖에 없음