0

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: let the returned array be of size n)??? (I am using Java Eclipse) I have created the RandomArray, however I do not know how to put it in an ArrayList, this is what I've got so far:

    import java.util.Random;
    public class Lab6 {

    public static void main(String[] args) {

    Random random = new Random();
    int[] n = new int[1];

    for( int i = 0 ; i < n.length ; i++ ) { 
       for ( int i1 = 0 ; i1 < n.length ; i1++ ) { 
          n[i1] = random.nextInt(255);
       }
    }
    for( int a : n ) { 
        System.out.println( a );
    }
}
    }
goat
  • 31,486
  • 7
  • 73
  • 96
howzat
  • 49
  • 1
  • 2
  • 12

5 Answers5

1

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.

MAK
  • 26,140
  • 11
  • 55
  • 86
1

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;
}
dimo414
  • 47,227
  • 18
  • 148
  • 244
Matthew Cox
  • 13,566
  • 9
  • 54
  • 72
  • @user1086318 Np. It's important that you understand what is going on here though. I missed the homework tag, normally I wouldn't just hand out a complete solution but ooooops =P – Matthew Cox Dec 08 '11 at 00:13
  • thanks, yes i would definitely want to know whats going on otherwise its pointless to do!!! – howzat Dec 08 '11 at 00:24
  • Worth mentioning that creating new `Random` objects on every invocation isn't a great idea. Especially in earlier versions of Java this could lead to very un-random data being returned. An easy way around this is to use `ThreadLocalRandom.current()`, but storing a single static `Random` object would work just as well for single-threaded executions. – dimo414 May 23 '13 at 03:27
0

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 :)

dimo414
  • 47,227
  • 18
  • 148
  • 244
0

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;

}
Johnny Rocket
  • 1,394
  • 3
  • 17
  • 25
  • You are trying to add ints to a collection of type Integer. This would result in a compiler error. – Matthew Cox Dec 08 '11 at 00:15
  • I assure you it won't. Where would the compiler error come from? – Johnny Rocket Dec 08 '11 at 00:18
  • Unless new versions of Java will perform an implicit cast from int to Integer then it will (I haven't done a lot since 1.4.2). You are trying to add an variable `next` of type `int` into a typed generic collection `newArrayList` that requires objects of type `Integer`. – Matthew Cox Dec 08 '11 at 00:20
  • 1
    Java 1.5 and up supports autoboxing, so this conversion will be performed for you. – Ray Dec 08 '11 at 00:35
0

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));
    }
}
Jaime Hablutzel
  • 6,117
  • 5
  • 40
  • 57