• 泛型数组随机排列工具类


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

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

     

    ☞源代码:

    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

     

  • 相关阅读:
    Redis持久化
    Redis进阶——事务、TTL、排序、消息通知、管道
    行为设计模式
    Redis数据类型
    ASP.NET并发处理
    c# 泛型有什么作用?
    IBatisNet 升级到 .Net Framework 4.0 时发现 IBatisNet 一小BUG
    【Python3】用for循环和while循环分别打印出如下格式“九九乘法表”
    Visual Studio 2010 SP1 WPF程序属性重命名BUG,小心!
    为什么用SOA架构?
  • 原文地址:https://www.cnblogs.com/wzjhoutai/p/6707817.html
Copyright © 2020-2023  润新知