java将hashmap键作为整数数组获取

Kri*_*dra 2 java integer hashmap

我有这样的哈希映射

public HashMap <String,People> valueHashMap  = new Hashmap();
Run Code Online (Sandbox Code Playgroud)

这里我的HashMap的关键是以字符串为单位的秒数,即我正在像这样向hashmap添加值

long timeSinceEpoch = System.currentTimeMillis()/1000;
valueHashMap.put(
                   Integer.toString((int)timeSinceEpoch)
                   , people_obj
                );
Run Code Online (Sandbox Code Playgroud)

现在我想将hashmap中的所有键都放入整数数组列表中.

ArrayList<Integer> intKeys = valueHashMap.keys()...
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

dac*_*cwe 11

没有直接的方法将Strings 列表转换为s列表Integer:

  1. 你需要重新定义valueHashMap这样的:

    public HashMap<Integer, People> valueHashMap  = new HashMap<Integer, People>();
    
    ....
    
    ArrayList<Integer> intKeys = new ArrayList<Integer>(valueHashMap.keySet());
    
    Run Code Online (Sandbox Code Playgroud)
  2. 或者你需要循环:

    ArrayList<Integer> intKeys = new ArraList<Integer>();
    
    for (String stringKey : valueHashMap.keySet())
         intKeys.add(Integer.parseInt(stringKey);
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我会建议你使用Longas键代替:

    public HashMap<Long, People> valueHashMap  = new HashMap<Long, People>();
    
    Run Code Online (Sandbox Code Playgroud)

    然后就没有施法int (你可以用上面的(1)Long代替).

  • 使用`Long`的+1将有助于避免[2038年问题](http://en.wikipedia.org/wiki/Year_2038_problem). (2认同)