泛型数组随机排列工具类

前言:近期开发一款简易游戏。要将一个数组中的内容随机排列。

考虑到以后可重用性,所以自己写了一款“泛型数组随机排列工具类”,如今分享给大家,希望能给大家带来启示。假设有好的方法类,请发给笔者邮箱,大家互相学习,感激不尽。

 

☞源代码:

  1. import java.lang.reflect.Array;
  2. import java.util.Random;
  3.  
  4. /**
  5.  * 泛型数组随机排列工具类。
  6.  *
  7.  * 要求:使用类类型。
  8.  *
  9.  * 演示样例:
  10.  *
  11.  * public static void main(String[] args) {     
  12.  *     Integer[]is1 = {1,2,3,4,5,6};    
  13.  *     is1= ArrayRandomPermutation.random(Integer.class,is1);    
  14.  *     for(inti=0;i<is1.length-1;i++){
  15.  *         System.out.print(is1[i]+",");
  16.  *     }System.out.print(is1[is1.length-1]);//避免最后一个值带“,”    
  17.  *  }
  18.  *
  19.  * @author fzb
  20.  * 2014-07-14
  21.  */
  22. public final class ArrayRandomPermutation {
  23.  
  24.     public static <T> T[] random(Class<T> type, T[] array) {
  25.        Random rd = new Random();
  26.        @SuppressWarnings("unchecked")
  27.        T[] temp = (T[])Array.newInstance(type, array.length);
  28.        int num;
  29.  
  30.        boolean[] bool = new boolean[array.length];
  31.        for (int i = 0; i < array.length; i++) {
  32.            do {
  33.               num = rd.nextInt(array.length);
  34.            } while (bool[num]);
  35.            bool[num] = true;
  36.            temp[i] = array[num];
  37.        }
  38.        return temp;
  39.     }
  40.  
  41. }
  42.  

 

如有好的建议,可留言或发至笔者邮箱:fzb_xxzy@163.com

 

原文地址:https://www.cnblogs.com/wzjhoutai/p/6707817.html