「Java」HashMapを利用するサンプル

書式
new HashMap<クラス名, String>
サンプルコード

package com.arkgame.study;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class HashMapTest {

      public static void printElements(Collection<Student> c, HashMap<Student, String> hp) {
            Iterator<Student> it = c.iterator();
            while (it.hasNext()) {
                  Object objKey = it.next();
                  System.out.println("キー:" + objKey + " = " + hp.get(objKey));
            }
      }

      public static void main(String[] args) {

            // HashMap<クラス名,String>
            HashMap<Student, String> hp = new HashMap<Student, String>();

            Student sd1 = new Student(11, "name001");
            Student sd2 = new Student(22, "name002");
            Student sd3 = new Student(33, "name003");

            hp.put(sd1, "value11");
            hp.put(sd2, "value22");
            hp.put(sd3, "value33");

            Set<Student> keys = hp.keySet();
            System.out.println("キーの値は下記:");

            printElements(keys, hp);
      }
}

//Studentクラスの定義
class Student {
      int num;
      String name;

      Student(int num, String name) {
            this.num = num;
            this.name = name;
      }

      // hashCode
      public int hashCode() {
            return num * name.hashCode();
      }

      public boolean equals(Object o) {
            Student s = (Student) o;
            return num == s.num && name.equals(s.name);
      }

      public String toString() {
            return num + ":" + name;
      }

}

実行結果
キーの値は下記:
キー:33:name003 = value33
キー:11:name001 = value11
キー:22:name002 = value22

Java

Posted by arkgame