Amos的随笔

Java/Python/Go,软件测试等等

导航

Java List 随机取值的多种方法

为了从列表中获取随机元素,需要生成一个随机索引号,然后使用list.get()方法通过生成的索引编号获取元素。

这里关键是要记住,不得使用超过列表大小的索引。

方法 1

 public static void main(String[] args) {

     List<String> list = Arrays.asList("a","b","c");
     int index = (int) (Math.random()* list.size());
     System.out.println(list.get(index));
 }

方法 2

 public static void main(String[] args) {

     List<String> list = Arrays.asList("a","b","c");
     int index = new Random().nextInt(list.size());
     System.out.println(list.get(index));
 }

方法 3

 public static void main(String[] args) {

     List<String> list = Arrays.asList("a","b","c");

     // shuffle 打乱顺序 
     Collections.shuffle(list);
     System.out.println(list.get(0));
 }

posted on 2018-04-24 16:44  AmosChen  阅读(100)  评论(0)    收藏  举报  来源