简体   繁体   中英

Java - HashSet: Is iterator not random access?

I know the underlying data structure for the hashset is an array. I thought I can get a random value from the hashset by using iterator().next().

I looked at the source code but couldn't really tell. Does iterator not traverse the values in the hashset in a random order?

The iterator will traverse the elements by hash table bucket which is based on the hash code of the objects, and thus they will be in an arbitrary order which might certainly seem random, however they will be consistent for a given HashSet size and contents. Because the order is arbitrary, hash-based containers make no guarantees about the iteration order of their elements, but they do not make any effort to randomize the order.

Random Access in terms of data structures means that you can get the elements in an array-like operation using an index. It lets you select any location by specifying the aforementioned index. Lists are also random access as they have a get() method. If you want to get the elements in a random order other you could put them in a List and then shuffle the list.

List<Integer> list = new ArrayList<>(List.of(1,2,3,4,5,6,7,8,9));   
Collections.shuffle(list);
for (int i : list) {
    System.out.println(i);
}

prints something like the following without repeated elements.

4
5
3
7
6
1
9
8
2

If you want to just get values randomly including possible repeated elements. Then use Random as suggested and generate a random index from 0 to list.size() and retrieve the value using list.get() . You could do that as long as required without exhausting the supply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM