[Java] 노트정리 : HashMap

Young eee·2023년 2월 24일

Java

목록 보기
21/22
post-thumbnail

📖 HashMap

  • 키와 값의 쌍으로 이루어진 데이터의 집합
    순서는 유지X / 키는 중복값을 허용X / 값은 중복 허용

💻 ArrayList Ex.

Ex1

Map<Integer, String> hMap = new HashMap<Integer, String>();
		
		// 추가
		hMap.put(101, "Lions");
		hMap.put(102, "Tigers");
		hMap.put(103, "Bears");
		hMap.put(104, "Twins");
		// 중복 허용x 키값에 새로운 값을 넣으면 값이 바뀜
		hMap.put(102, "Giants");
		
		System.out.println(hMap.size());
		
		// 모두 출력
		// iterator : 반복자(== 포인터(주소)) == cursor
		Iterator<Integer> it = hMap.keySet().iterator(); // 제일 첫 번째 주소를 가져옴
		while(it.hasNext()) {
			Integer key = it.next();	// 키값을 꺼내면서 다음으로 이동
			String value = hMap.get(key);
			System.out.println(key + ":" + value);
		}
		
		// 삭제
		String deleteValue = hMap.remove(104);
		System.out.println("삭제된 value : " + deleteValue);
		
		// 검색
		//		value			key
		String value = hMap.get(101);
		
		boolean b = hMap.containsKey(102);
		if(b == true) {
			String val = hMap.get(102);
			System.out.println(val);
		}
		
		// 수정
		hMap.replace(103, "Eagles");
		
		it = hMap.keySet().iterator(); // 제일 첫 번째 주소를 가져옴
		while(it.hasNext()) {
			Integer key = it.next();	// 키값을 꺼내면서 다음으로 이동
			String val = hMap.get(key);
			System.out.println(key + ":" + val);
		}

Ex2

package hashmap;

import java.util.HashMap;
import java.util.Scanner;

public class HashMapEx1 {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<>();
		map.put("myId", "1234");
		map.put("asdf", "1111");
		map.put("asdf", "1234");
		
		System.out.println(map);
		
		Scanner sc = new Scanner(System.in);
		
		while(true) {
			System.out.println("id와 password를 입력해주세요");
			System.out.print("id :");
			String id = sc.next().trim();
			
			System.out.println("password : ");
			String password = sc.next().trim();
			System.out.println();
			
			if(!map.containsKey(id)) {
				System.out.println("입력하신 id는 존재하지 않습니다. 다시 입력해주세요");
				continue;
			}
			
			if(!(map.get(id).equals(password))) {
				System.out.println("비밀번호가 일치하지않습니다. 다시 입력해주세요");
			} else {
				System.out.println("id와 비밀번호가 일치합니다");
				break;
			}
		}
	}
}

0개의 댓글