본문 바로가기
JAVA

[java] Map예제 - map을 이용해 이름으로 전화번호 검색 하기

by 자바비터 2022. 4. 2.

▶ map을 이용하여 이름으로 전화번호 검색하기

package kh1229;

import java.util.HashMap;
import java.util.Scanner;

public class HashMap2 {
	public static void main(String[] args) {
		//학생 이름과 Student 객체를 쌍으로 저장하는 HashMap 컬렉션 생성
		HashMap<String, Student> map = new HashMap<String, Student>();
		
		//3명의 학생 저장
		map.put("임창균", new Student(1, "010-1111-1111"));
		map.put("이민혁", new Student(2, "010-2222-2222"));
		map.put("유기현", new Student(3, "010-3333-3333"));
		
		Scanner sc = new Scanner(System.in);
		
		while(true) {
			System.out.print("검색할 이름?");
			String name = sc.nextLine(); //사용자로부터 이름 입력
			if(name.equals("exit")) //exit 입력하면 프로그램 종료
				break;
			
			Student student = map.get(name); //이름에 해당하는 Student 객체 검색
			//name이 키. 저장되는 건 키값인 Student 객체
			if(student == null)
				System.out.println(name + "은 없는 사람입니다.");
			else
				System.out.println("num : " + student.num +", 전화번호 : " + student.tel);
		}
		sc.close();
	}
}

class Student <T, V> {
	T num;
	V tel;
	public Student(T num, V tel) {
		this.num = num;
		this.tel = tel;
	}
}

실행 결과 화면

  

map에서 중요한건 키(Key)와 값(value) 한 세트로 저장된다는 것이며, 객체를 값으로 사용할 수 있다.

 

댓글