Backend

<Backend> Java / HashMap 응용

이게왜 2023. 11. 6. 18:56

https://rezerocodinglife.tistory.com/22

 

Start <명품JAVA> ArrayList

명품자바의 예제문제, 실습문제를 풀며 공부해 나갑니다. 목표는 Collection, Generic, Comparable, Comparator, Iterable, Iterator, Stream, Lambda Expression등을 공부하여 이를 활용한 몬테카를로 시뮬레이션 미니 프

rezerocodinglife.tistory.com

공부를 시작하며 작성한 글 입니다. 공부하며 사용한 자료들이 있으니 참고하시면 좋겠습니다.

 

https://rezerocodinglife.tistory.com/23

 

<JAVA Backend> HashMap

https://rezerocodinglife.tistory.com/22 Start ArrayList 명품자바의 예제문제, 실습문제를 풀며 공부해 나갑니다. 목표는 Collection, Generic, Comparable, Comparator, Iterable, Iterator, Stream, Lambda Expression등을 공부하여 이

rezerocodinglife.tistory.com

지난 글에서 공부한 간단한 HashMap 예제 입니다.  이번글에서는 더 나아가 HashMap의 Parameter(매개변수)에 Object(객체)를 넣어서 구현하는 예제를 풀어보겠습니다.

 

<HashMap 문제>

  1. id와 tel(전화번호)로 구성되는 Students 클래스를 만들고, 이름을 'key'로 하고 Student 객체를 'Value'로 하는 해시맵을 작성하라.

(명품 JAVA p.418)

package self_Generic;

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

public class Exercise7_7 {
    public static void main(String[] args) {
        Exercise7_7 user1 = new Exercise7_7();
        user1.insertStuInfo();
        user1.researchStuInfoByName();
    }

    private HashMap<String, Students> studentInfo;
    private static final int STUDENT_NUM = 3;

    public void insertStuInfo() {
        studentInfo = new HashMap<>();
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < STUDENT_NUM; i++) {
            System.out.print((i + 1) + " 학생 이름을 입력하세요 >> ");
            String name = sc.nextLine().trim();
            System.out.print((i + 1) + " 학생 ID를 입력하세요 >> ");
            String id = sc.nextLine().trim();
            System.out.print((i + 1) + " 학생 전화번호를 입력하세요 >> ");
            String tel = sc.nextLine().trim();

            this.studentInfo.put(name, new Students(id, tel));
        }
    }

    public void researchStuInfoByName() {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.print("검색할 학생의 이름을 입력하세요 >> ");
            String inputName = sc.nextLine().trim();
            if (inputName.equals("exit")) {
                System.out.println("프로그램 종료...");
                break;
            }
            Students result = getStuInfo(inputName);
            if (result == null) {
                System.out.println("등록되지 않은 학생입니다. 다시 입력하세요.");
            } else {
                System.out.println(result);
            }
        }
        sc.close();

    }

    public Students getStuInfo(String inputName) {
        return this.studentInfo.get(inputName);
    }

}

class Students {
    private String id;
    private String tel;

    public Students(String id, String tel) {
        this.id = id;
        this.tel = tel;
    }

    public String toString() {
        return "ID : " + this.id + "\n"
                + "Tel : " + this.tel;
    }
}
이 코드에서 중요한 Method는 insertStuInfo 라고 생각합니다.
public void insertStuInfo() {
        studentInfo = new HashMap<>();
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < STUDENT_NUM; i++) {
            System.out.print((i + 1) + " 학생 이름을 입력하세요 >> ");
            String name = sc.nextLine().trim();
            System.out.print((i + 1) + " 학생 ID를 입력하세요 >> ");
            String id = sc.nextLine().trim();
            System.out.print((i + 1) + " 학생 전화번호를 입력하세요 >> ");
            String tel = sc.nextLine().trim();

            this.studentInfo.put(name, new Students(id, tel));
        }
    }
Student Class의 instance variableid, tel을 Scanner로 입력받았습니다.
HashMap StudentInfo의 KeyName 또한 Scanner로 입력받았습니다.

this.studentInfo.put(name, new Students(id, tel)) 를 살펴보겠습니다.
method는 내부 -> 외부 순으로 실행됩니다.

new Student(id, tel)이 실행되고 put(name, ..)이 실행됩니다.

put(method)는 put(key, value) 형태입니다.
"new Student(id, tel)에서 생성된 Student 객체가 put 메소드의 두 번째 매개변수인 값(value)의 위치에 들어가게 됩니다."

즉, HashMap의 Key-Value 쌍에서 Keyname이 되고, Valuenew Student(id, tel)에서 생성된 Student 객체가 됩니다.
이를 이용해 
name을 사용하여 해당 학생의 정보를 검색하는 researchStuInfoByName 메소드를 구현 가능합니다.

 

'Backend' 카테고리의 다른 글

<Backend> Java / Generic 예제문제 2  (3) 2023.11.08
<Backend> Java / Generic 예제문제  (2) 2023.11.07
<Backend> Java / Stack, Generic  (3) 2023.11.06
<Backend> Java / HashMap  (0) 2023.11.06
Start <명품JAVA> ArrayList  (2) 2023.11.06