티스토리 뷰

개발/Java

Map 컬렉션

욱스다 2022. 9. 5. 15:24

Map 컬렉션의 특징 및 주요 메소드

특징

- 키(key)와 값(Value)으로 구성된 Map.Entry 객체를 저장하는 구조

- 키와 값은 모두 객체

- 키는 중복될 수 없지만 값은 중복 저장 가능

 

구현 클래스

-HashMap, Hashtable, LinkedHashMap, Properties, TreeMap

 

주요 메소드

기능
메소드
설명
객체 추가
V put(K ket, V value)
주어진 키와 값을 추가,
저장이 되면 값을 리턴
객체 검색
boolean containsKey(Object key)
주어진 키가 있는 지 여부
boolean containsValue(Object value)
주어진 값이 있는지 여부
set<Map.Entry<K,V>> entrySet()
키와 값의 쌍으로 구성된 모든
Map.Entry객체를 Set에 담아서 리턴
V get(Object key)
주어진 키의 값을 리턴
boolean isEmpty()
컬렉션이 비어있는지 여부
Set<K> keyset()
모든 키를 Set에 담아서 리턴
int size()
저장된 키의 총 수를 리턴
Collection<V> values()
저장된 모든 값 Collection 에 담아서 리턴
객체 삭제
void clear()
모든 Map.Entry(키와 값)를 삭제
V remove(Object key)
주어진 키와 일치하는 Map.Entry 삭제,
삭제가 되면 값을 리턴

 

객체 추가, 찾기, 삭제


Map<String, Integer> map = ~...;

map.put("홍길동","30"); // 객체 추가
int score = map.get("홍길동") // 객체 찾기
map.remove("홍길동"); // 객체 삭제
 

전체 객체를 대사으로 반복해서 얻기

Ver1. map.Keyset 이용법

Map<K, V> map = ~;
Set<K> keySet = map.keySet();
Iterator<K> keyIterator = keySet.iterator();
while(keyIterator.hasNext){
K key = keyIterator.next();
V value = map.get(key);
}
 

 

Ver2. map.entrySet이용법

Set<Map.Entry<K, V>> entrySet = map.entrySet();
Iterator<Map.Entry<K, V>> entryItertator = entrySet.iterator();
while(entryIterator.hasNext()){
Map.Entry<K, V> entry = entryItetrator.next();
K key = entry.getKey();
V value = entry.getValue();
}
 

*Hashtable

Map<K, V> map = new Hashmap<K, V> ();
 

특징

- 키 객체는 Hashcode(), equals() 를 재정의해서 동등 객체가 될 조건을 정해야 한다.

-Hashtable은 스레드 동시화(synchronization)가 되어 있기 때문에

복수의 스레드가 동시에 Hashtable에 접근해서 객체를 추가, 삭제하더라도 스레드에 안전(thread safe)하다.

 

*멀티스레드에서는 HashMap 대신 Hashtable을 사용해야함

*싱글스레드에서는 HashMap

 

package chap15.sec04.exam02_hashtable;

import java.util.Hashtable;
import java.util.Map;
import java.util.Scanner;


public class HashtableExample {

	public static void main(String[] args) {
		Map<String, String> map = new Hashtable<String, String>();
		
		map.put("spring", "12");
		map.put("summer", "123");
		map.put("fall", "1234");
		map.put("winter", "12345");
		
		Scanner scanner = new Scanner(System.in);
		
		while(true) {
			System.out.println("아이디와 비밀번호를 입력해주세요");
			System.out.print("아이디: ");
			String id = scanner.nextLine();
			
			System.out.print("비밀번호: ");
			String password = scanner.nextLine();
			System.out.println();
			
			if(map.containsKey(id)) {
				if(map.get(id).equals(password)) {
					System.out.println("로그인 완료");
					break;
				} else {
					System.out.println("비밀번호가 일치하지 않습니다.");
				}
			} else {
				System.out.println("존재하는 아이디가 없습니다.");
			}
		}

	}

}
 

맵을 db처럼 이용한 예제.

 

Properties

- 키와 값을 String 타입으로 제한한 Map컬렉션

- Properties는 프로퍼티(~.Properties) 파일을 읽어 들일 때 주로 사용한다.

프로퍼티(~.Properties) 파일

- 옵션 정보, 데이터베이스 연결 정보, 국제화(다국어) 정보를 기록한 텍스트 파일로 활용

- 애플리케이션에서 주로 변경이 잦은 문자열을 저장해서 유지 보수를 편리하게 만들어 줌

- 키와 같이 = 기호로 연결되어 있는 텍스트 파일로 ISO 8859-1 문자셋으로 저장

ex) driver = oracle.jdbc.OracleDriver

url= ghfhgf

username = lee

password = 444

- 한글은 유니코드(Unicode)로 변환되어 저장

contry = 대한민국 x

contry = \uB300\uD55C\uBBFC\uAD6D O

language = 한글 x

language = \uD55C\uAE00 O

 

'개발 > Java' 카테고리의 다른 글

throws 예외처리  (0) 2022.09.15
Set 컬렉션  (0) 2022.09.05
List 컬렉션  (0) 2022.09.05
인스턴스 멤버와 this  (0) 2022.09.04
정적 멤버와 static  (0) 2022.09.04
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함