一个简单的:
我试图使用构造函数创建对象,但是我的对象创建为空。构造函数位于同一包中的不同类中。
public static void main(String[] args) {
//Initialize all data:
ArrayList<Airport_example> all_airports = new ArrayList<Airport_example>();
Airport_example perth = new Airport_example("01","Perth","PER","Australia","WST");
Airport_example brisbane = new Airport_example("02","Brisbane","BNE","Australia","EST");
//Add airports to ArrayList
all_airports.add(perth);
all_airports.add(brisbane);
//debugging
System.out.println(all_airports);
}
单独类中的构造函数如下所示:
public class Airport_example extends HashMap<String,String> {
//list of variables
private String airportID;
private String city;
private String code3;
private String country;
private String timezone;
// constructor to initialize objects
public Airport_example(String airportID, String city, String code3, String country, String timezone) {
// Constructor variable initialization
this.airportID = airportID;
this.city = city;
this.code3 = code3;
this.country = country;
this.timezone = timezone;
}
}
System.out.println语句返回一个空数组。我错过了一个简单的把戏吗?
[{}, {}]
您的构造函数工作正常;问题是您正在扩展aHashMap
并期望它知道Airport_example
子类的私有字段的内容。要使打印语句按预期方式工作,必须重写该toString
方法。
我建议将您的代码更改为以下内容:
public class Airport_example {
private String airportID;
private String city;
private String code3;
private String country;
private String timezone;
public Airport_example(String airportID, String city, String code3, String country, String timezone) {
this.airportID = airportID;
this.city = city;
this.code3 = code3;
this.country = country;
this.timezone = timezone;
}
}
public String toString() {
// replace the string you want each object to print out
return this.airportID + ", " + this.city + ", " + this.code3 + ", " + this.country + ", " + this.timezone;
}
打印空数组的原因是它当前正在调用HashMap
的toString
,并且由于您未定义任何HashMap
字段,因此将其视为empty HashMap
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句