Web Design, Development & Marketing

Web Development Articles

Java: Random Array Generator

The following Java code can be used when wanting to create an array containing random elements. You can easily specify the length of the array and the range of values that the random elements can take.

The randomIntArray() Java method shown below returns an array that contains random elements.

// creates random array of elements of value 0 to n-1
public static int[] randomIntArray(int length, int n)
{
  int[] a = new int[length];
  Random generator = new Random();
  // for each item in the list
  for (int i = 0; i < a.length; i++)
  {
      // create a new random number and populate the
      // current location in the list with it
      a[i] = generator.nextInt(n);
  }
  return a;
}

Subscribe to RSS Feed Bookmark and Share

Related Links

Related Articles / Posts

Java: Quick Sort Algorithm Analysis (13/06/2006)

Java: Merge Sort Algorithm Analysis and Code (05/04/2006)

Java: Random Array Generator (29/03/2006)

Java: Insertion Sort Algorithm Analysis and Code (29/03/2006)

Java: Binary Search Algorithm Analysis and Code (29/03/2006)