我有这样的代码:
public Flight{
String code;
char status;
char type;
Flight(String code, char status, char type){
this.code = code;
this.status = status;
this.type = type;
}
}
public Menu{
Flight flight1 = new Flight("DL123",'A','D');
Flight flight2 = new Flight("DL146",'A','I');
flightMap.put("DL123", flight1)
flightMap.put("DL146", flight2)
}
if(schedule.flightMap.containsKey(decision))
{
}
如果用户输入 DL123 并且 containsKey 返回 true,我想返回仅 flight1 的对象属性。我怎么能做到这一点?我试过覆盖 toString 但因为 toString 只能作为字符串返回,所以我不知道如何返回作为字符的状态和类型属性。
请询问您是否需要更多信息!
最佳答案
在 Flight
类中定义 getter
方法,然后:
if(schedule.flightMap.containsKey(decision)){
Fligth matchingFlight = schedule.flightMap.get(decision);
String code = matchingFlight.getCode();
char status = matchingFlight.getStatus();
char type = matchingFlight.getType();
}
关于java - 从 HashMap 中只打印一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13984101/