How to select a random key from a HashMap in Java?

前端 未结 9 1118
小鲜肉
小鲜肉 2021-02-05 05:03

I\'m working with a large ArrayList>, and I would repeatedly need to select a random key from a random HashMap (and do some stuff with it).

9条回答
  •  失恋的感觉
    2021-02-05 05:47

    You need access to the underlying entry table.

    // defined staticly
    Field table = HashMap.class.getDeclaredField("table");
    table.setAccessible(true);
    Random rand = new Random();
    
    public Entry randomEntry(HashMap map) {
        Entry[] entries = (Entry[]) table.get(map);
        int start = rand.nextInt(entries.length);
        for(int i=0;i

    This still has to traverse the entries to find one which is there so the worst case is O(n) but the typical behaviour is O(1).

提交回复
热议问题