キーを整数としてハッシュマップを作成する必要があり、異なるデータ型の複数の値を保持する必要があります。たとえば、キーが msg id で、値が
- 文字列型のメッセージ
- 時間型のタイムスタンプ
- 整数型のカウント
- 整数型のバージョン
それでは、単一のキーを持つ異なるデータ型の値をハッシュマップに格納する方法は?
独自のデータ クラスがない場合は、次のようにマップを設計できます。
Map<Integer, Object> map=new HashMap<Integer, Object>();
ここで、MAP から値を取得するときに「instanceof」演算子を使用することを忘れないでください。
独自の Data クラスがある場合は、次のようにマップを設計できます
Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapTest {
public static void main(String[] args) {
Map<Integer,Demo> map=new HashMap<Integer, Demo>();
Demo d1= new Demo(1,"hi",new Date(),1,1);
Demo d2= new Demo(2,"this",new Date(),2,1);
Demo d3= new Demo(3,"is",new Date(),3,1);
Demo d4= new Demo(4,"mytest",new Date(),4,1);
//adding values to map
map.put(d1.getKey(), d1);
map.put(d2.getKey(), d2);
map.put(d3.getKey(), d3);
map.put(d4.getKey(), d4);
//retrieving values from map
Set<Integer> keySet= map.keySet();
for(int i:keySet){
System.out.println(map.get(i));
}
//searching key on map
System.out.println(map.containsKey(d1.getKey()));
//searching value on map
System.out.println(map.containsValue(d1));
}
}
class Demo{
private int key;
private String message;
private Date time;
private int count;
private int version;
public Demo(int key,String message, Date time, int count, int version){
this.key=key;
this.message = message;
this.time = time;
this.count = count;
this.version = version;
}
public String getMessage() {
return message;
}
public Date getTime() {
return time;
}
public int getCount() {
return count;
}
public int getVersion() {
return version;
}
public int getKey() {
return key;
}
@Override
public String toString() {
return "Demo [message=" + message + ", time=" + time
+ ", count=" + count + ", version=" + version + "]";
}
}
次のようなJava言語の異なるタイプの変数がいくつかあります。
message of type string
timestamp of type time
count of type integer
version of type integer
次のような HashMap を使用する場合:
HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put("message","message");
yourHash.put("timestamp",timestamp);
yourHash.put("count ",count);
yourHash.put("version ",version);
yourHash を使用する場合:
for(String key : yourHash.keySet()){
String message = (String) yourHash.get(key);
Datetime timestamp= (Datetime) yourHash.get(key);
int timestamp= (int) yourHash.get(key);
}
Define a class to store your data first
public class YourDataClass {
private String messageType;
private Timestamp timestamp;
private int count;
private int version;
// your get/setters
...........
}
次に、マップを初期化します。
Map<Integer, YourDataClass> map = new HashMap<Integer, YourDataClass>();
次のプロパティを持つオブジェクトを適切な名前で作成します。
これをマップの値として使用します。
また、オブジェクトの等価性を比較に使用したくない場合 (たとえば、マップに値を挿入する場合) は、 equals()およびhashCode()メソッドを適宜オーバーライドすることを検討してください。