HashMap은 인터페이스 종류 중 하나로써
Key, Value 값으로 데이터를 저장하는 형태를 가지고 있다.
여기서 Map은 Key와 Value를 쌍으로 묶어 저장하는 컬렉션 클래스를 구현하는 데 사용이 된다.
--> Key,Value 값으로 저장하는 List 형태의 조상
Hashtable, HashMap, LinkedHashMap, SortedMap, TreeMap 등 Map 종류는 다양하다.
hashing(해싱)이라는 검색 방법을 사용하기 떄문에 많은 양의 데이터를 검색하는 데 있어서 유용하다.
여기서! HashMap의 Value값은 중복저장이 가능하지만, Key는 중복 저장이 불가능하고,
기존의 저장된 키와 동일한 키로 값을 저장하면 기존의 값은 없어지고 새로운 값으로 대체를 한다.
Map 컬렉션 공통 메서드
기능 | 메서드 | 설명 |
객체 추가 | V put(K key, V value) | 주어진 키로 값을 저장 새로운 키일 경우 null 리턴 |
객체 검색 | 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() | 모든 key를 Set 객체에 담아서 리턴 | |
int size() | 저장된 key의 총 수를 리턴 | |
Collection<> values() | 저장된 모든 값을 Collection에 담아서 리턴 | |
객체 삭제 | void clear() | 모든 Map.Entry(키와 값) 삭제 |
V remove(Object key) | 주어진 key와 일치하는 Map. Entry를 삭제하고 값을 리턴 |
기본적인 사용방법
public class TestHashMap {
//Map에 데이터 넣기 (Key,Value)
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("aaa",new Integer(10));
map.put("bbb",new Integer(20));
map.put("ccc",new Integer(30));
//Key 중 "aaa" Key를 가질 경우 true 리턴
if(map.containsKey("aaa")) {
System.out.println("aaa");
}
//Key,Value를 Set에 담고 iterator에 Set 정보를 담기
Set<Entry<String,Integer>>set = map.entrySet();
Iterator<Entry<String,Integer>>iter = set.iterator();
//Key,Value 값 호출
while(iter.hasNext()) {
Map.Entry<String,Integer> e =
(Map.Entry<String, Integer>)iter.next();
System.out.println(e.getKey() + e.getValue());
}
//저장된 Key를 가져올 Set 만들기
Set<String> set2 = map.keySet();
System.out.println(set2);
//value값들을 Collection<Integer>형태로 얻어 오고 iterator에 담기
Iterator<Integer> iter2;
Collection<Integer> values= map.values();
iter2=values.iterator();
int total=0;
while(iter2.hasNext()) {
Integer i = (Integer)iter2.next();
total+=i.intValue();
}
예제1
import java.util.*;
public class C07MapMain {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
if(!map.containsKey("aaa")) {
map.put("aaa",1234);
}
if(!map.containsKey("bbb")) {
map.put("aaa",1234);
}
if(!map.containsKey("aaa")) {
map.put("aaa",9999);
}
// 키 중복을 방어하기 위한 if문. map에 "aaa"라는 key가 존재하지 않는다면
// "aaa" key 넣기 --> map은 중복된 key를 저장할 수 없다
// 마지막 if문에서 첫번 째 if문 구절과 같은 key 값이 저장이 되는데
// 출력을 하면 key "aaa" 에 value 9999 만 출력이 된다
// -> 중복이 될 시 마지막에 저장된 key 값이 저장이 된다.
// 모든 key 수집(Set)
Set <String> set = map.keySet();
// Iterator 를 통한 key 순회
Iterator<String> iter = set.iterator();
// 각각 key에 해당되는 value 추출
while(iter.hasNext()) {
String key = iter.next(); // key 값을 받는다.
int value = map.get(key); // key에 대응되는 value 꺼낸다.
System.out.println("KEY : " + key + ", VALUE : " + value);
}
}
예제2
import java.util.*;
public class C08MapMain {
public static void main(String[] args) {
int num = 0;
Scanner input = new Scanner(System.in);
Map<String, String> map = new HashMap();
while(true) {
System.out.println("========M E N U==========");
System.out.println("1 ID/PW 등록");
System.out.println("2 ID/PW 조회");
System.out.println("3 Password 변경");
System.out.println("4 ID 삭제");
System.out.println("5 전체 조회");
System.out.println("6 종료");
System.out.println("========M E N U==========");
System.out.print("번호 : ");
num = input.nextInt();
Set<String> set = map.keySet();
Iterator<String> iter = set.iterator();
switch (num) {
//map 에 ID/PW 등록
//기존에 동일 id가 있으면 등록 불가(containsKey)
case 1:
System.out.println("ID / PW 등록 메뉴 입니다.");
System.out.print("ID : ");
String ID = input.next();
System.out.print("PW : ");
String PW = input.next();
if(!map.containsKey(ID)) {
map.put(ID, PW);
}else{
System.out.println("중복된 ID가 존재합니다.");
}
break;
case 2:
System.out.print("조회 하실 ID 를 입력 하세요 : ");
String id = input.next();
while(iter.hasNext()) {
String key = iter.next();
String pw = map.get(key);
System.out.println(key + "가 조회 되었습니다.");
System.out.println("조회하신 ID의 비밀번호는 : " + pw + " 입니다." );
System.out.println("초기 화면으로 돌아갑니다.");
break;
}
break;
//ID를 받아서 map에 id/pw 출력
case 3:
System.out.print("비밀번호 변경 메뉴 입니다. ID를 입력하세요 : ");
String replace = input.next();
if(map.containsKey(replace)) {
System.out.print("변경 할 비밀번호를 입력 하세요 : ");
String pw = input.next();
map.put(replace, pw);
}else{
System.out.println("해당 ID가 없습니다.");
}
//ID를 받아서 map에 있는 동일한 id의 password 변경
break;
case 4:
System.out.print("삭제 할 ID 를 입력하세요 : ");
String removeid = input.next();
if(map.containsKey(removeid)) {
map.remove(removeid);
System.out.println("삭제 완료 되었습니다.");
}else {
System.out.println("아이디가 존재하지 않습니다.");
}
break;
//ID를 받아서 map에 있는 동일한 id 삭제
case 5:
System.out.println("등록한 ID 전체 조회 ");
while(iter.hasNext()) {
String name = iter.next();
String Pass = map.get(name);
System.out.println("ID : " + name + ", PASSWORD : " + Pass);
}
case 6:
System.out.println("프로그램 종료");
System.exit(-1);
default:
System.out.println("다시 입력...");
}
}
}
}
'Backend > JAVA' 카테고리의 다른 글
[JAVA] MVC Pattern (0) | 2022.05.09 |
---|---|
[JAVA] ServerSocket (0) | 2022.05.02 |
[JAVA] chatAt(int i) - '0' (0) | 2022.04.23 |
[JAVA] 상속(Inheritance) (0) | 2022.04.22 |
[JAVA] Singleton Pattern (0) | 2022.04.21 |