2017-10-27 1 views
0

나는 할 수있는 프로그램이있다. 그것은 말합니다 :다른 클래스의 값을 hashMap에 저장하는 방법은 무엇입니까?

아래와 같이 데이터의 처음 세 부분은 객체로 구성되어 안전하게 저장됩니다. 세 가지 데이터는 성명, 객실 번호 및 객실 가격입니다.

은 내가 hashMap를 사용하는 것을 생각 그렇게하려면 다음은 해시 맵의 키는 main

Map<Integer, DoubleValue> record = new HashMap<Integer, DoubleValue>(); 

roomNumber로이다;

public class DoubleValue { 

    String fullName; 
    int roomPrice; 

    public DoubleValue(String fullName, int roomPrice){ 

     this.fullName = fullName; 
     this.roomPrice = roomPrice; 

     } 
    } 

그래서, 나는 세 개의 매개 변수를받는 구조로 클래스 고객을 사례 : fullNameroomPrice 클래스 이것은 해시 맵에 두 개의 값을 저장하는 클래스 DoubleValue입니다 DoubleValue

에서 왔습니다.

public class Guest { 

    private String fullName; 
    private int doubleValue; //I don't know if is this is correct 


    //Constructor 
    public Guest(){ 
    } 


    public Guest(String fullName, int DoubleValue){ 
     this.fullName = fullName; 
     this.doubleValue = DoubleValue; 

    } 
... // continue with methods 
} 

이제 질문은 다음과 같습니다

  1. 어떻게 새로운 객체를 생성하고, 게스트 클래스를 참조 키 값을 저장하기 위해?

    Guest customer = new Guest(key,?); 
    
  2. 값을 받아들이려면 게스트가 필요합니까?

    공공 고객

+0

당신에게 해시 맵이 좋습니다 확신을 ? 2 명의 손님이 같은 객실 번호를 사용한다면 어떻게 될까요? – Solace

+0

@Solace : 방이 독특하고 운동을 쉽게하기 때문에 좋은 생각 인 것 같습니다. 나중에 합병증이 생깁니다. – SwampThing

+0

세 가지 매개 변수를 사용하여 게스트를 만들지 않는 이유를 이해하지 못합니다. 당신이 한 것처럼 가격 (또는 roomNumber)을 추가하면 doubleValue가 무엇을 의미하는지 알 수 없습니다. – idipous

답변

0

이 더 나은 해결책이 될 수 있지만, HashMap의 선택으로가는 당신은 다음과 같이 생성자를 가질 수 있지만 (문자열 fullName의,있는 doubleValue (?)를 INT).

public Guest(String fullName, int roomNum, int roomPrice){ 
    this.fullName = fullName; 
    this.doubleValue = new DoubleValue(fullName, roomPrice); 
    record.put(roomNum, this.doubleValue); // record is your HashMap as per the question content, if its maintained in another class you may need a way to acess it or a method to put values in it. 
} 
+0

답변이 좋습니다. 나에게 그것은 플러스 하나 ...;) –

0

당신은 룸과 고객의 개체를 분할 할 수 있으며, 고객이 객실 수 :

import java.util.ArrayList; 
import java.util.List; 

public class Guest { 
    String fullName; 
    Room room; 

    public Guest(String fullName, Room room) { 
     this.fullName = fullName; 
     this.room = room; 
    } 

    public static void main(String[] args) { 
     List<Guest> guests = new ArrayList<Guest>(); 
     Room room324 = new Room(324, 500.45); 
     Guest guest1 = new Guest("John Smith", room324); 

     guests.add(guest1); 
    } 
} 

그리고 바로 객실 :

public class Room { 
    int number; 
    double price; 

    public Room(int number, double price) { 
     this.number = number; 
     this.price = price; 
    } 
} 
+0

무엇? 왜 아래 투표? 내가 틀린 것을 이해 했는가? –

+0

나는 거기에 많은 잘못이 있다고 생각한다. 나의 대답보다 좋다 ... 심지어 나는 이유를 알아 내려고 노력하고있다. ... –

+2

@ nits.kk 예 ... 나는 누군가가 downvotes 아무런 설명이 없다면 누군가가 어떻게 나아질 수 있겠는가? –

관련 문제