Hashmap 持有不同的数据类型作为值,例如 Integer、String 和 Object [英] Hashmap holding different data types as values for instance Integer, String and Object

查看:26
本文介绍了Hashmap 持有不同的数据类型作为值,例如 Integer、String 和 Object的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个键为整数的哈希图,它应该包含多个不同数据类型的值.例如,如果键是 msg id,值是

I need to create a hashmap with key as integer and it should hold multiple values of different data types. For example if the key is msg id and the values are

  1. 字符串类型的消息
  2. 时间类型的时间戳
  3. 整数类型的计数
  4. 整数类型的版本

那么如何将单个key的不同数据类型的值存储到hashmap中呢?

Then how to store the values of different data type with a single key into the hashmap?

推荐答案

如果你没有自己的Data Class,那么你可以如下设计你的地图

If you don't have Your own Data Class, then you can design your map as follows

Map<Integer, Object> map=new HashMap<Integer, Object>();

在从 MAP 检索值时,不要忘记使用instanceof"运算符.

Here don't forget to use "instanceof" operator while retrieving the values from MAP.

如果您有自己的数据类,那么您可以按如下方式设计地图

If you have your own Data class then then you can design your map as follows

地图<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 + "]";
    }

}

这篇关于Hashmap 持有不同的数据类型作为值,例如 Integer、String 和 Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆