我有一个像这样的 HashMap
public HashMap <String,People> valueHashMap = new Hashmap();
这里我的 HashMap 的关键是以秒为单位的字符串时间,即我像这样向 hashmap 添加值
long timeSinceEpoch = System.currentTimeMillis()/1000;
valueHashMap.put(
Integer.toString((int)timeSinceEpoch)
, people_obj
);
现在我想将 HashMap 中的所有键放入整数数组列表中。
ArrayList<Integer> intKeys = valueHashMap.keys()...
有什么办法可以做到这一点吗?
最佳答案
没有直接的方法将String
列表转换为Integer
列表:
您需要像这样重新定义
valueHashMap
:public HashMap<Integer, People> valueHashMap = new HashMap<Integer, People>(); .... ArrayList<Integer> intKeys = new ArrayList<Integer>(valueHashMap.keySet());
或者你需要循环:
ArrayList<Integer> intKeys = new ArraList<Integer>(); for (String stringKey : valueHashMap.keySet()) intKeys.add(Integer.parseInt(stringKey);
不过,我建议您使用
Long
作为键:public HashMap<Long, People> valueHashMap = new HashMap<Long, People>();
那么就不会转换为
int
(您可以使用上面的 (1) 和Long
来代替)。
关于java 获取 HashMap 键作为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7412597/