How to create an ArrayList from array? Element[] array = {new Element(1), new Element(2), new Element(3)}; How do I convert the above variable of type Element[] into a variable of type ArrayList<Element>? ArrayList<Element> arrayList = ...;
Home/arraylist
Java 7+ In Java 1.7 or later, the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max]) is as follows: import java.util.concurrent.ThreadLocalRandom; // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randoRead more
Java 7+
In Java 1.7 or later, the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max]) is as follows:
See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.
However, conversely with ThreadLocalRandom there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar.
Java 17+
As of Java 17, the psuedorandom number generating classes in the standard library implement the
RandomGenerator
interface. See the linked JavaDoc for more information. For example, if a cryptographically strong random number generator is desired, theSecureRandom
class can be used.Earlier Java
Before Java 1.7, the standard way to do this is as follows:
See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().
In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.
See less