Skip to content

Latest commit

 

History

History
309 lines (246 loc) · 7.58 KB

220309.md

File metadata and controls

309 lines (246 loc) · 7.58 KB

HashMap과 Hashtable

Map 인터페이스를 구현. 데이터를 키와 값의 쌍으로 저장
HashMap(동기화X)은 Hashtable(동기화O)의 신버젼
TreeMap은 TreeSet과 같이 이진 탐색 트리이다.

Map

  • Hashtable
  • HashMap
    • LinkedHashMap
  • SortedMap
    • TreeMap

HashMap

  • Map 인터페이스를 구현한 대표적인 컬렉션 클래스
  • 순서를 유지하려면, LinkedHashMap클래스를 사용

TreeMap

  • TreeSet과 같은 특성을 가짐
  • 범위 검색과 정렬에 유리한 컬렉션 클래스
  • HashMap보다 데이터 추가, 삭제에 시간이 더 걸림

HashMap의 키와 값

해싱기법으로 데이터를 저장. 데이터가 많아도 검색이 빠르다.
키는 컬렉션 애의 키중에서 유일해야 한다.
값은 키와 달리 데이터의 중복을 허용한다.

public class HashMap extends AbstractMap implements Map, Cloneable, Serializable {
    transient Entry[] table;
    ...
    static class Entry implements Map.Entry {
        final Object key;
        Object value;
        ...
    }
}
// 비객체지향적인 코드
Object[] key;
Object[] value;

// 객체지향적인 코드
Entryp[] table;
class Entry {
    Object key;
    Object value;
}

해싱

해시함수는 키값을 넣으면 저장위치(해쉬코드)를 알려준다.
해시함수로 해시테이블에 데이터를 저장, 검색하는 것을 해싱이라고 한다.

해시테이블은 배열과 링크드 리스트가 조합된 형태

해시테이블에 저장된 데이터를 가져오는 과정

  1. 키로 해시함수를 호출해서 해시코드를 얻는다.
  2. 해시코드에 대응하는 링크드리스트를 배열에서 찾는다.
  3. 링크드리스트에서 키와 일치하는 데이터를 찾는다.
  • 해시 함수는 같은 키에 대해 항상 같은 해시코드를 반환해야 한다. 서로 다른 키일지라도 같은 값의 해시코드를 반환할 수도 있다.

HashMap의 메소드

package ch02;

import java.util.*;

public class EX3 {

	public static void main(String[] args) {
		HashMap map = new HashMap();
		map.put("myId",  "1234");
		map.put("asdf",  "1111");
		map.put("asdf",  "1234");
		
		Scanner s = new Scanner(System.in);
		
		while(true) {
			System.out.println("id와 password를 입력해주세요.");
			System.out.print("id : ");
			String id = s.nextLine().trim();
			
			System.out.print("password : ");
			String password = s.nextLine().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;
			}
		}
	}
	
}

id와 password를 입력해주세요.
id : asdf
password : 1111111111

비밀번호가 일치하지 않습니다. 다시 입력해주세요.
id와 password를 입력해주세요.
id : asdf
password : 1234

id와 비밀번호가 일치합니다.

package ch02;

import java.util.*;

public class EX3 {

	public static void main(String[] args) {
		HashMap map = new HashMap();
		map.put("A", new Integer(90));
		map.put("B", new Integer(100));
		map.put("C", new Integer(100));
		map.put("D", new Integer(80));
		map.put("E", new Integer(90));
		
		Set set = map.entrySet(); // key value 쌍
		Iterator it = set.iterator();
		
		while(it.hasNext()) {
			Map.Entry e = (Map.Entry)it.next();
			System.out.println("이름 : " + e.getKey()+", 점수 : "+e.getValue());
		}
		
		set = map.keySet();
		System.out.println("참가자 명단 : "+set);
		
		Collection values = map.values();
		it = values.iterator();
		
		int total = 0;
		
		while(it.hasNext()) {
			int i = (int)it.next();
			total += i;
		}
		
		System.out.println("총점 : "+total);
		System.out.println("평균 : "+(float)total/set.size());
		System.out.println("최고점수 : "+Collections.max(values));
		System.out.println("최저점수 : "+Collections.min(values));
	}
	
}

이름 : A, 점수 : 90
이름 : B, 점수 : 100
이름 : C, 점수 : 100
이름 : D, 점수 : 80
이름 : E, 점수 : 90
참가자 명단 : [A, B, C, D, E]
총점 : 460
평균 : 92.0
최고점수 : 100
최저점수 : 80

package ch02;

import java.util.*;

public class EX3 {

	public static void main(String[] args) {
		String[] data  = {"A","K","A","K","D","K","A","K","K","K","Z","D"};
		
		HashMap map = new HashMap();
		
		for(int i=0; i<data.length; i++) {
			if(map.containsKey(data[i])) {
				int value = (int)map.get(data[i]);
				map.put(data[i], value + 1);
			} else {
				map.put(data[i], 1);
			}
		}
		
		Iterator it = map.entrySet().iterator();
		
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			int value = (int)entry.getValue();
			System.out.println(entry.getKey()+" : "+printBar("#", value)+" "+value);
		}
	}
	
	public static String printBar(String str, int value) {
		String result = new String();
		for(int i=0; i<value; i++) {
			result = result + str;
		}
		return result;
	}
	
}

A : ### 3
D : ## 2
Z : # 1
K : ###### 6

Collections

컬렉션을 위한 메소드(static)를 제공

  1. 컬렉션 채우기, 복사, 정렬, 검색
    • fill(), copy(), sort(), binarySearch(), ...
  2. 컬렉션 동기화
    • synchronizedXXX()
  3. 변경불가(readOnly) 컬렉션 만들기
    • unmodifialbeXXX()
  4. 싱글톤 컬렉션 만들기 (객체 1개만 저장)
    • singletonXXX()
  5. 한 종류의 객체만 저장하는 컬렉션 만들기
    • checkedXXX()
package ch02;

import java.util.*;
import static java.util.Collections.*;

public class EX3 {

	public static void main(String[] args) {
		List list = new ArrayList();
		System.out.println(list);
		
		addAll(list, 1, 2, 3, 4, 5);
		System.out.println(list);
		
		rotate(list, 2); //반시계방향으로 두 번 회전
		System.out.println(list);
		
		swap(list, 0, 2); // 첫 번쨰와 세 번쨰를 교환
		System.out.println(list);
		
		shuffle(list); // 저장된 요소의 위치를 임의로 변경
		System.out.println(list);
		
		sort(list, reverseOrder()); // 역순 정렬 reverse(list);와 같은 결과 출력
		System.out.println(list);
		
		sort(list); // 정렬
		System.out.println(list);
		
		int idx = binarySearch(list, 3); // 3이 저장된 위치
		System.out.println("index of 3 = "+idx);
		
		System.out.println("max="+max(list));
		System.out.println("min="+min(list));
		System.out.println("min="+min(list, reverseOrder()));
		
		fill(list, 9); // list를 9로 채운다.
		System.out.println(list);
		
		// list와 같은 크기의 새로운 list를 생성하고 2로 채운다. 단, 결과는 변경불가.
		List newList = nCopies(list.size(), 2);
		System.out.println("newList="+newList);
		
		System.out.println(disjoint(list, newList)); // 공통요소가 없으면 true 반환
		
		copy(list, newList);
		System.out.println("newList="+newList);
		System.out.println("list="+list);
		
		replaceAll(list, 2, 1);
		System.out.println("list="+list);
		
		Enumeration e = enumeration(list);
		ArrayList list2 = list(e);
		
		System.out.println("list2="+list2);
	}	
}

[]
[1, 2, 3, 4, 5]
[4, 5, 1, 2, 3]
[1, 5, 4, 2, 3]
[4, 1, 3, 2, 5]
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
index of 3 = 2
max=5
min=1
min=5
[9, 9, 9, 9, 9]
newList=[2, 2, 2, 2, 2]
true
newList=[2, 2, 2, 2, 2]
list=[2, 2, 2, 2, 2]
list=[1, 1, 1, 1, 1]
list2=[1, 1, 1, 1, 1]

컬렉션 클래스 정리 & 요약

정리