java 随机从数组中取一个元素,在org.apache.commons.lang3中,有没有比较好用的工具类
是的,在org.apache.commons.lang3中有一个比较好用的工具类可以实现随机取数组元素的功能,那就是RandomUtils。使用RandomUtils可以方便地从数组中取一个随机元素,代码示例如下:
import org.apache.commons.lang3.RandomUtils;
public class RandomArrayElement {
public static void main(String[] args) {
String[] array = {"apple", "banana", "orange", "pear", "peach"};
String element = RandomUtils.nextItem(array);
System.out.println("Random element: " + element);
}
}
在上述代码中,先定义了一个字符串数组array,然后使用RandomUtils.nextItem(array)方法随机取一个元素,最后输出结果。需要注意的是,RandomUtils.nextItem()方法只适用于数组中元素类型相同的情况,如果数组中元素类型不同,则需要使用其他方法实现随机取元素的功能。
原文地址: https://www.cveoy.top/t/topic/uLz 著作权归作者所有。请勿转载和采集!