▶ 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) 한 세트로 저장된다는 것이며, 객체를 값으로 사용할 수 있다.
'JAVA' 카테고리의 다른 글
java 컬렉션(Collection) shuffle() 메소드를 이용한 간단하나 카드게임 만들기 (1) | 2022.04.05 |
---|---|
[java] Set이란? (+HashSet, TreeSet 예제) (0) | 2022.04.03 |
java 컬렉션(Collection)이란? (+ 예제) (0) | 2022.03.29 |
java 제네릭(Generic)이란? (0) | 2022.03.26 |
java 래퍼클래스(Wrapper class)란? (0) | 2022.03.24 |
댓글