如何使用 getValue 从 HashMap 中获取更多的值
How to get more the one values froma HashMap with getValue
我正在 JAVA 中编写程序并且我正在使用 HashMap。
private HashMap<Integer,Plane> planes;
飞机是class我创造的:
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。我该如何解决这个问题?
您需要为 Plane class,
覆盖并添加 toString 方法
@Override
public String toString() {
return "Plane [planeNumber=" + planeNumber +
",departureTime=" + departureTime +
",arrivalTime=" + arrivalTime +
",flightDuration=" + flightDuration +
",aerialDrops=" + aerialDrops + "]";
}
现在你正在使用 Object class parent
的 toString 方法
根据您的需要稍作改动即可:
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
}
}
我正在 JAVA 中编写程序并且我正在使用 HashMap。
private HashMap<Integer,Plane> planes;
飞机是class我创造的:
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。我该如何解决这个问题?
您需要为 Plane class,
覆盖并添加 toString 方法 @Override
public String toString() {
return "Plane [planeNumber=" + planeNumber +
",departureTime=" + departureTime +
",arrivalTime=" + arrivalTime +
",flightDuration=" + flightDuration +
",aerialDrops=" + aerialDrops + "]";
}
现在你正在使用 Object class parent
的 toString 方法根据您的需要稍作改动即可:
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
}
}