2017-01-15 15 views
-2

私はHashMapを持っています。クラスのすべてのキー値と属性を出力したいと思います。 私のクラスがある:私は整数2010から2014への例えば年間、クラス国がその年の全ての国や人口になりますHashMapを作成したい、と後でHashMapを印刷することHashMap <String、Class>

class Country { 
    String country; 
    int population; 

Country(String country, int population) { 
    this.country=country; 
    this.population=population; 
    } 
} 

、国名と人口を収集しています。

int year=1960; 
HashMap<Integer,Country> country =new HashMap<Integer, Country>(); 
for (int j=0; j<10; j++)           
{ 
    String country=countrylist[j]);  
    int population=populationlist[j]);  
    Country P=new Country(country,population);  
    country.put(year, P);   

    year++; 

} 

for (Map.Entry p : country.entrySet()) { 
    Country country=(Country)p.getValue(); 
    year=(Integer)p.getKey(); 
    nameCountry=country.country; 
    population=country.population; 
    println(year,namecountry,population); 
} 
+1

okです。質問は何ですか?あなたが立ち往生した特定の部分はありますか? –

+0

私が紹介した最後のクラスだけを取得していますので、最後の国、印刷しようとします。 –

+0

int year = 2010;国P =新しい(countryName、Population); Country.put(年、P); –

答えて

1

あなたの問題は、あなたが「地図」ではなく「マルチマップ」の後にいることです。区別は、 'マルチマップ'を使用して各キーに複数の値を格納できることです。あなたの場合、毎年複数の国/人口エントリが必要です。

標準Java APIにはマルチマップ実装はありません。多くのサードパーティの実装があります。マルチマップを検索すると束が見つかります。

マップ内の値としてコレクションを持つことによって、標準Javaを使用して同様のことを達成することは可能です。

あなたのケースでは、別のデータ構造を検討することをお勧めします。

Map<Integer,Map<String,Integer>> populationData; 

新しい年のデータを格納するために、あなたはどうなる:国が唯一、毎年1人の人口を有していてもよく、より良い構造があるかもしれないので

populationData.put(2017, new HashMap<>()); 

と国のためにデータを保存します1年:

populationData.get(2017).put("Botswana", 45982637); 
+0

ありがとう、大きな助け –

関連する問題