2012-05-06 12 views
0

Iの値としてキーと学生オブジェクトとしてstudentIdsを保持するハッシュマップ、JavaでHashMapからオブジェクトを取得していますか?

HashMap<Integer, Student> hashMap = hashTables.buildHash(students); 

public static HashMap<Integer, Student> buildHash(Student[] students) { 
      HashMap<Integer, Student> hashMap = new HashMap<Integer, Student>(); 
      for (Student s : students) hashMap.put(s.getId(), s); 
      return hashMap; 
     } 

以下のコードは、それぞれです。KeyValueペアとs.getValueを(取得を持っている)は、IDから構成されている学生のオブジェクトと文字列を返します名前、これらの値を取得/印刷する方法(student.int、student.name);

for(Map.Entry<Integer, Student> s : hashMap.entrySet()) 
    System.out.print(s.getKey()+" "+s.getValue().getId()+" "+s.getValue().getName()); 

(つまり、言語のキーワードなので、クラスは「INT」という名前のフィールドを持つことは不可能だということに注意してください):

for(Map.Entry s : hashMap.entrySet()) 
    System.out.print(s.getKey()+" "+s.getValue()); 

答えて

3

は、あなただけのエントリのパラメータ化された型を使用する必要があります。

+0

@Marko Topolnikことで、これをacheiveすることができます:私が使っていたという理由だけで彼のクラスの構造についてOPの構文違反の情報 –

+0

もちろん、私はそれのユーモラスな側面を実現しました。それを模倣するよりも助けてほしいです:) HashMapの人口コードではゲッターを使っているので、おそらく 'id'と' name'はプライベートであるはずです。 –

3

ただ、学生にtoStringを実装し、あなたが投稿したコードはそのままで動作します。

public class Student { 
    ... 
    public String toString() { 
     return "ID = " + this.id + ", name = " + this.name; 
    } 
} 
+0

とにかく、オブジェクトのint値とstring値を取得できますか? –

+1

Michael Borgwardtの答えを参照してください、彼はそれをカバーしています。ポイントは 'Map.Entry'の宣言で型パラメータを使うことです。次に、 'e.getValue()。getId()'を自由に書くことができます。 –

1

あなたは...

for(Map.Entry<Integer, Student> s : hashMap.entrySet()){ 
    System.out.print(Long.valueof(s.getKey())+""+String.valueof(s.getValue().getName())); 
} 
関連する問題