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

后端 未结 5 460
夕颜
夕颜 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:31

    Try something like this

    private ArrayList<Integer> randomArray(int size){
    Random random = new Random();
    
    ArrayList<Integer> newArrayList = new ArrayList<Integer>();
    
    for(int i=0; i<size; i++){
    int next = random.nextInt(256);
    newArrayList.add(next);
    }
    
    return newArrayList;
    
    }
    
    0 讨论(0)
  • 2021-01-17 05:31

    This is more than you asked for, but it's tangentially related, and might help people coming across this question.

    When you want an ArrayList of random integers, you often really just need some random numbers, and don't really need them stored anywhere. In such a case, you likely can get away with just an Iterator<Integer> that returns a stream of random integers, as many as you need. This is very easy to do with the Guava library (which nowadays should be part of every Java codebase).

    You can easily define an Iterator<Integer> that gives you as many random ints (or any other data type you want) as you ask for:

    public static final Iterator<Integer> RAND_INT_ITER =
        new AbstractIterator<Integer>() {
            @Override
            protected Integer computeNext() {
                return ThreadLocalRandom.current().nextInt();
            }
        };
    

    Or if you want to use the Random.nextInt(int max) method:

    public static Iterator<Integer> randIntIterator(final int max) {
        return new AbstractIterator<Integer>() {
            @Override
            protected Integer computeNext() {
                return ThreadLocalRandom.current().nextInt(max);
            }
        };
    }
    

    There's no issue with calling this method wherever you need it, since it stores no state you're not wasting time or space computing anything, and the garbage collector will clean it up for you when you're done. We use ThreadLocalRandom to ensure these are thread-safe and avoid constructing new Random objects all over the place (and the potential data-race conditions that introduces, though newer versions of Java are pretty smart about that). You could just as easily use an existing Random object if that made more sense.

    Some examples:

    // print random ints until we see one that's divisible by 100
    while(true) {
        int rnd = RAND_INT_ITER.next();
        System.out.println(rnd);
        if(rnd % 100 == 0) {
            break;
        }
    }
    
    // Get an iterator of exactly 10 random ints, [0,255)
    Iterator<Integer> tenRandInts = Iterators.limit(randIntIterator(255), 10);
    while(tenRandInts.hasNext()) {
        System.out.println(tenRandInts.next());
    }
    
    // Note that the returned iterator above is still one-use, if you need to iterate
    // Over the same numbers more than once, put them in a list first
    // It's not a good idea to simply convert an Iterator into an Iterable, see:
    // http://stackoverflow.com/a/14711323/113632
    List<Integer> randIntLs = ImmutableList.copyOf(
                                  Iterators.limit(randIntIterator(255), 10));
    for(int rnd : randIntLs) {
        System.out.println(rnd);
    }
    for(int rnd : randIntLs) {
        System.out.println(rnd);
    }
    

    Using this pattern for random data generation will often make your code cleaner, leaner, and easier to read. Give it a try :)

    0 讨论(0)
  • 2021-01-17 05:42

    You mean something like this:

    public ArrayList<Integer> randomArrayList(int n)
    {
        ArrayList<Integer> list = new ArrayList<>();
        Random random = new Random();
    
        for (int i = 0; i < n; i++)
        {
            list.add(random.nextInt(255));
        }
        return list;
    }
    
    0 讨论(0)
  • 2021-01-17 05:49

    ArrayLists work in much the same way as arrays, except they can grow (or shrink) as you want and do not support access/retrieval via the [] operator (i.e. you can't do n[i1] on an ArrayList). Instead, use its add() method to add elements to it and get() method to access elements.

    0 讨论(0)
  • 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<Integer> integers = RandomArray(n);
    
            for (Integer integer : integers) {
                System.out.println(integer);
            }
    
    
        }
    
        private static ArrayList<Integer> 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<Integer>(Arrays.asList(ints));
        }
    }
    
    0 讨论(0)
提交回复
热议问题