2017-05-14 17 views
2

単純なものJavaコンストラクタが同じパッケージ内で動作しない

オブジェクトを作成するためにコンストラクタを使用しようとしていますが、オブジェクトが空に作成されています。コンストラクタは、同じパッケージ内の別のクラスに存在します。

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文は、空の配列を返します。私はここで簡単なトリックを逃したことがありますか?

[{}, {}] 
+3

なぜ 'HashMap.toString()'が 'Airport_example'のプライベートフィールドについて知りたいのですか?さらに、なぜあなたは 'HashMap'を最初に拡張していますか? – Siguza

+0

なぜあなたはハッシュマップを拡張しますか? –

+1

コンストラクタはうまく動作します... –

答えて

6

コンストラクタは正常に動作します。問題は、HashMapを拡張し、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のいずれかを定義していないとして、それが現在、HashMaptoStringを呼び出し、そしてだということですフィールドには、それが空のHashMapとして扱われています。

関連する問題