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

특징

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

키와 값은 모두 객체

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

구현클래스

HashMap,    Hashtable,    LinkedHashMap,    Properties,    TreeMap

기능 

메소드 

설명 

객체

추가 

  V put(K key, 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("홍길동")             //객체 삭제

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

Map<K,V> map = ~ ;

Set<K> keySet = map.keySet();

Iterator<K> keyIterator = keySet.iterator();


while(keyIterator.hasNext()){

K Key = key.Iterator.next();

V value = map.get(key);

}




Set<Map.Entry<K,V> entrySet = map.entrySet();

Iterator<Map.Entry<K.V>> entryIterator = entrySet.iterator();


while(entryIterator.hasNext()){

Map.Entry<K, V> entry = entryIterator.next();

K key = entry.getKey();

V value = entry.getValue();

}



HashMap

특징

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

키 타입은 String를 많이 사용

String은 문자열이 같을 경우 동등 객체가 될수 있도록
hashCode()와 equals() 메소드가 재정의 되어 있기 때문

Exam

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();

map.put("김나박", 85);
map.put("김범수", 90); //중복저장 키가 같음
map.put("박정현", 80);
map.put("김범수", 95); //중복저장 키가 같음 새로운 값으로 대체

System.out.println("총 Entry 수 " + map.size());
System.out.println(map.get("김범수"));

System.out.println();

Set<String> keySet = map.keySet();
Iterator<String> keyIterator = keySet.iterator();

while (keyIterator.hasNext()) {
String key = keyIterator.next();
Integer value = map.get(key);
System.out.println("\t" + key + ":" + value);
}
System.out.println();

map.remove("김범수");
System.out.println("총 Entry 수 : " + map.size());

Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
Iterator<Map.Entry<String, Integer>> entryIterator = entrySet.iterator();
while (entryIterator.hasNext()) {
Map.Entry<String, Integer> entry = entryIterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("\t" + key + ": " + value);
}
map.clear(); // 전체 삭제
System.out.println("총 Entry 수 : " + map.size());
}
} 결과 총 Entry 수 3 95 김범수:95 김나박:85 박정현:80 총 Entry 수 : 2 김나박: 85 박정현: 80 총 Entry 수 : 0

Exam2

public class Student {
public int sno;
public String name;

public Student(int sno, String name) {
this.sno = sno;
this.name = name;
}

@Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student student = (Student) obj;
return sno == student.sno && name.equals(student.name);
} else {
return false;
}
}

@Override
public int hashCode() {
return sno + name.hashCode();
}
}
import java.util.HashMap;
import java.util.Map;

public class HashMapExample2 {
public static void main(String[] args) {
Map<Student, Integer> map = new HashMap<>();

map.put(new Student(1, "김나박"), 95);
map.put(new Student(1, "김나박"), 90);

System.out.println("총 Entry 수 : " + map.size());

System.out.println(map.get(new Student(1,"김나박")));

}
}



Hashtable

특징

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

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

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


Exam 

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<>();
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("아이디가 존재하지 않습니다.");
}
}
}
} 결과 아이디와 비밀번호를 입력해 주세요 아이디: spring 비밀번호: 13 비밀번호가 틀렸습니다. 아이디와 비밀번호를 입력해 주세요 아이디: spring2 비밀번호: 13 아이디가 존재하지 않습니다. 아이디와 비밀번호를 입력해 주세요 아이디: spring 비밀번호: 12 로그인 되었습니다.



Properties

특징

키와 값을 String 타입으로 제한한 Map 컬렉션이다.

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


프로퍼티(~.properties) 파일

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

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

database.properties       키 = 값으로 구성된 프로퍼티

driver = oracle.jdbc.OracleDriver
url = jdbc:oracle:thin@localhost:1521:orcl
username = scott
password = tiger


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

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

contry = 대한민국  X          ->   contry = \xB300\xD55C\xBBFC\xAD6D


Properties 객체 생성

파일 시스템 경로를 이용

Properties properties = new Properties();
properties.load(new FileReader("C:/~/database.properties"));    ----------  파일의 경로


ClassPath를 이용

String path = 클래스.class.getResource("database.properties").getPath();    
path = URLDecoder.decode(path, "utf-8");      -------------      경로에 한글이 있을 경우
Properties properties = new Properties();
properties.load(new FileReader(path));

String path = A.class.getResource("config/database.properties").getPath();

값 읽기

String value = properties.getProperty("key");



Exam

import java.io.FileReader;
import java.net.URLDecoder;
import java.util.Properties;

public class PropertiesExample {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();

String path = PropertiesExample.class.getResource("database.properties").getPath();

path = URLDecoder.decode(path, "utf-8"); //한글이 있을수 있으니 디코더사용
properties.load(new FileReader(path));

String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("driver = " + driver);
System.out.println("url = " + url);
System.out.println("username = " + username);
System.out.println("password = " + password);
}


+ Recent posts