return an ArrayList of Integers that consist of n random numbers?

后端 未结 5 480
夕颜
夕颜 2021-01-17 05:17

How do I create the method RandomArray and let it take in an integer n and return an ArrayList of Integers that consist of n random numbers between 0 and 255.(in other words

5条回答
  •  不知归路
    2021-01-17 05:49

    Main method contains an example usage

    import java.security.*;
    import java.util.*;
    
    
    public class Util {
    
        public static void main(String[] args) {
            int n = 15;
    
            ArrayList integers = RandomArray(n);
    
            for (Integer integer : integers) {
                System.out.println(integer);
            }
    
    
        }
    
        private static ArrayList RandomArray(int n) {
            Random rand = new SecureRandom();
            byte[] b = new byte[n];
            rand.nextBytes(b);
            Integer[] ints = new Integer[b.length];
            for (int i = 0; i < b.length; i++) {
                ints[i] = b[i] & 0xFF;
            }
            return new ArrayList(Arrays.asList(ints));
        }
    }
    

提交回复
热议问题