泛型数组随机排列工具类

前言:最近开发一款简易游戏,要将一个数组中的内容随机排列。考虑到以后可重用性,所以自己写了一款“泛型数组随机排列工具类”,现在分享给大家,希望能给大家带来启发。如果有好的方法类,请发给笔者邮箱,大家互相学习,感激不尽。

 

☞源码:

  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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值