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
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
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
that gives you as many random ints (or any other data type you want) as you ask for:
public static final Iterator RAND_INT_ITER =
new AbstractIterator() {
@Override
protected Integer computeNext() {
return ThreadLocalRandom.current().nextInt();
}
};
Or if you want to use the Random.nextInt(int max)
method:
public static Iterator randIntIterator(final int max) {
return new AbstractIterator() {
@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 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 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 :)