0

我正在用 JAVA 编写程序,并且正在使用 HashMap。

 private HashMap<Integer,Plane> planes;

Plane 是我创建的一个类:

public class Plane {
   private int planeNumber;
   private int departureTime;
   private int arrivalTime;
   private int flightDuration;
   private int aerialDrops;

   //constructors...
}

然后我尝试像这样打印 HashMap 的所有组件:

public void getAllAircrafts ()
{
    Set set = planes.entrySet();
    Iterator iterator = set.iterator();
    while(iterator.hasNext()) {
        Map.Entry mentry = (Map.Entry)iterator.next();
        System.out.print("Aircraft ID is: "+ mentry.getKey() + " ");
        System.out.println(mentry.getValue());
    }
}

问题是我想打印描述飞机的所有变量的值,但是我从mentry.getValue() 中得到了aircrafts.Plane@15db9742。我怎么解决这个问题?

4

2 回答 2

3

您需要为Plane类覆盖并添加一个toString方法,

    @Override
    public String toString() {
        return "Plane [planeNumber=" + planeNumber + 
                       ",departureTime=" + departureTime +  
                       ",arrivalTime=" + arrivalTime + 
                       ",flightDuration=" + flightDuration + 
                       ",aerialDrops=" + aerialDrops + "]";
    }

现在您正在使用 Object 类父级的 toString 方法

于 2017-12-02T09:40:14.087 回答
0

根据您的需要,稍作改动就可以了:

   public class Plane {
   private int planeNumber;
   private int planeNumber;
   private int arrivalTime;
   private int flightDuration;
   private int aerialDrops;

   public String toString()
{
  return planeNumber +" "+planeNumber+" "+arrivalTime+" "+flightDuration+" "+aerialDrops
}
}
于 2017-12-02T09:48:31.263 回答