해시맵 (HashMap)
- Map 인터페이스를 구현한 클래스
- 객체(Object)/인스턴스(Instance)를 대신할 수 있는 자료구조
- 용어
1) Entry : Key + Value를 합쳐서 부르는 말
2) Key : 데이터를 식별하는 식별자(변수명)
3) Value : 데이터 자체(변수에 저장된 값)
- 특징
1) Key는 중복이 불가능 (HashSet 구조로 되어 있다)
2) Value는 중복이 가능
3) Key와 Value 모두 Generic 처리한다
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class MainWrapper {
public static void main(String[] args) {
Map<String, Object> board1 = new HashMap<String, Object>();
board1.put("title", "제목1");
board1.put("writer", "작성자1");
board1.put("view", "10");
Map<String, Object> board2 = new HashMap<String, Object>();
board2.put("title", "제목2");
board2.put("writer", "작성자2");
board2.put("view", "20");
Map<String, Object> board3 = new HashMap<String, Object>();
board3.put("title", "제목3");
board3.put("writer", "작성자3");
board3.put("view", "30");
List<Map<String, Object>> boardList = new ArrayList<Map<String, Object>>();
boardList.add(board1);
boardList.add(board2);
boardList.add(board3);
for (int i = 0, length = boardList.size(); i < length; i++) {
Map<String, Object> board = boardList.get(i);
System.out.println("title: "+ board.get("title"));
System.out.println("writer: "+ board.get("writer"));
System.out.println("view: "+ board.get("view"));
for (Entry<String, Object> entry : board.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
- 맵은 여러개의 결과를 반환하고 싶을 때 자주 사용된다