What you could do, is store your resources into a List
, then randomly permutes it thanks to Collections.shuffle(List<?> list)
or shuffle(List<?> list, Random rnd)
, and finally call iterator()
on the resulting list to get an instance of Iterator
that you could store into a member field to be able to iterate over your list (thanks to hasNext()
/next()
) and remove your resource once done with remove()
.
Here is a pseudo code using String
as resource just to show the idea:
// Create a read/write list (Arrays.asList returns a read-only list)
List<String> resources = new ArrayList<>(Arrays.asList("1", "2", "3"));
System.out.printf("Initial state = %s%n", resources);
Collections.shuffle(resources);
System.out.printf("Permuted List = %s%n", resources);
Iterator<String> iterator = resources.iterator();
if (iterator.hasNext()) {
String resource = iterator.next();
// do something
iterator.remove();
System.out.printf("After remove = %s%n", resources);
}
Output:
Initial state = [1, 2, 3]
Permuted List = [3, 1, 2]
After remove = [1, 2]
NB: This approach makes sense in your case as you have a small list, please note that if you have a big list and you intend to retrieve only a small part of it, you should consider using a Random
to get randomly the index of the next element (using nextInt(int bound)
with list.size()
as parameter) to get (using get(int index)
) and remove (using remove(int index)
) instead of using Collections.shuffle(List<?> list)
as it would cause an overhead.
ArrayList
wouldn't work because I need to assign the color(value) to
the resource(key)
Yes it can work if you use a List
of a wrapper class that will contain both, your color and your resource (for example AbstractMap.SimpleImmutableEntry
or simply a custom class). It is good enough as you don't seem to need to retrieve the color by resource. If you do, you could simply have a Map
with resource as key and color as value and use new ArrayList<>(map.keySet())
to initialize your list of resources, then you will be able to apply what is proposed previously in this answer.