JAVA
컬렉션 프레임웤 HashMap
연93
2022. 10. 11. 22:03
import java.util.*;
import java.util.Map.Entry;
public class HashMapExample1 {
public static void main(String[] args) {
//컬렉션 특징의 기억장소 구조 key:value 형태로 설계. Entry 표현
Map<String, Integer> map = new HashMap<String, Integer>();
//데이터저장
map.put("김동연", 85);
map.put("송지은", 90);
map.put("송삼색", 80);
map.put("송지은", 95); // key가 중복되어 95가 저장되어 있음.
System.out.println("총 Entry 수: " + map.size()); // 3
//데이터 읽기(객체 찾기)
System.out.println("\t송지은 : " + map.get("송지은")); // 95
System.out.println();
//1)객체를 하나씩 처리. Iterator
Set<String> keySet = map.keySet(); // key정보로 Set으로 참조.
Iterator<String> keyInterator = keySet.iterator();
while(keyInterator.hasNext()) {
String key = keyInterator.next(); // key 정보를 읽어오고, 다음키로 위치가 이동.
Integer value = map.get(key);
System.out.println("\t" + key + " : " + value);
}
System.out.println();
//객체 삭제
map.remove("송지은");
System.out.println("총 Entry 수: " + map.size()); // 2
//2)객체를 하나씩 처리. Iterator -> Entry 형태로 Set참조작업
Set<Entry<String, Integer>> entrySet = map.entrySet();
Iterator<Entry<String, Integer>> entryIterator = entrySet.iterator();
while(entryIterator.hasNext()) {
Entry<String, Integer> entry = entryIterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("\t" + key + " : " + value);
}
System.out.println();
//객체 전체삭제
map.clear();
System.out.println("총 Entry 수: " + map.size());
}
}
import java.util.HashMap;
import java.util.Map;
public class HashMapExample2 {
public static void main(String[] args) {
/*
구조: key와value 라는 Entry 라는 단위로 관리된다.
- key는 중복이 되면 안된다.
- value는 중복허용.
객체저장시 중복부분을 해결해야 한다.
*/
Map<Student, Integer> map = new HashMap<Student, Integer>();
map.put(new Student(1, "김동연"), 95); // key로 힙영역의 주소가 참조가 된다.
map.put(new Student(1, "김동연"), 95);
System.out.println("총 Entry 수 : " + map.size());
}
}
public class Student {
public int sno;
public String name;
public Student(int sno, String name) {
this.sno = sno;
this.name = name;
}
// 동등객체로 비교하기위한 메소드 재정의
//첫번째 비교사용
@Override
public int hashCode() {
// TODO Auto-generated method stub
return sno + name.hashCode();
}
//두번째 비교사용
@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;
}
}
}