随机从_Set_集合中选择元素是各种Java应用程序中的常见需求,尤其是在游戏和数据处理任务中。
在本文中,我们将探讨从Java _Set_中选择随机元素的不同方法。
2. 使用_java.util.Random_类
_java.util.Random_类是生成随机数的便捷工具。要从_Set_中选择一个随机元素,我们可以生成一个随机索引,并使用它来访问元素:
public static ``<T>`` T getByRandomClass(Set``<T>`` set) {
if (set == null || set.isEmpty()) {
throw new IllegalArgumentException("The Set cannot be empty.");
}
int randomIndex = new Random().nextInt(set.size());
int i = 0;
for (T element : set) {
if (i == randomIndex) {
return element;
}
i++;
}
throw new IllegalStateException("Something went wrong while picking a random element.");
}
大约 2 分钟