仅从HashMap打印一个对象

时间:2012-12-21 04:02:51

标签: java object printing hashmap

我的代码如下:

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只能作为String返回,我不知道我是如何返回状态和类型属性的字符。

请询问您是否需要更多信息!

4 个答案:

答案 0 :(得分:3)

getter类中定义Flight方法,然后:

 if(schedule.flightMap.containsKey(decision)){
   Fligth matchingFlight = schedule.flightMap.get(decision);
   String code = matchingFlight.getCode();
   char status = matchingFlight.getStatus();
   char type = matchingFlight.getType();
 }

答案 1 :(得分:1)

飞行航班= schedule.flightMap.get(决定);

然后从飞行物体中,您可以检索所有值

答案 2 :(得分:1)

你需要的是

Flight flight = schedule.flightMap.get(decision);

使用这些可以简单地访问该对象,因为它们的可见性是默认的,如此

flight.code
flight.status

但更道德的方法是定义所有变量的getter和setter,如

public void setCode(String code)
{
     this.code = code;
}
public String getCode()
{
    return this.code;
}

这样你可以使用这个

来获取变量
String code = flight.getCode();

另请参阅

Why use getters and setters in java

答案 3 :(得分:0)

我试图解决你的问题并得出结论。见下面的代码。

package com.rais;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Rais.Alam
 * @project Utils
 * @date Dec 21, 2012
 */


public class FlightClient
{
/**
 * @param args
 */
public static void main(String[] args)
{
    Map<String,Flight> flightMaps = new HashMap<String, Flight>();
    Flight flight1 = new Flight("DL123", "STATUS-1", "TYPE-1");
    Flight flight2 = new Flight("DL124", "STATUS-2", "TYPE-2");
    Flight flight3 = new Flight("DL125", "STATUS-3", "TYPE-3");

    flightMaps.put("DL123", flight1);
    flightMaps.put("DL124", flight2);
    flightMaps.put("DL125", flight3);

    System.out.println(getValue(flightMaps, "DL123"));


}


public static String getValue(Map<String,Flight> flightMaps, String key)    
{
    if(flightMaps !=null && flightMaps.containsKey(key))
    {
        return flightMaps.get(key).status;
    }
    else
    {
        throw new RuntimeException("Flight does not exists");
    }


    }
}

    class Flight
    {
    String code;
    String status;
    String type;
    /**
     * @param code
     * @param status
     * @param type
     */
    public Flight(String code, String status, String type)
    {
        super();
        this.code = code;
        this.status = status;
        this.type = type;
    }



}