For example i want to make 10 Random object in java, but this code doesn't work, because an object name can't be an integer.
for(int i = 0; i < 10; i++)
{
Random i = new Random();
}
Any ideas?
You could build them into a List:
List<Random> randoms = new ArrayList<>();
for (int i = 0; i < 10; i++) {
randoms.add(new Random());
}
or an Array:
Random[] randoms = new Random[10];
for (int i = 0; i < randoms.length; i++) {
randoms[i] = new Random();
}
There are other options but these are the most common.
Use
for(int j = 0; j < 10; j++)
{
Random i = new Random();
}
instead should work.
But if it's me I'd like to use Stream.generate(Random::new).limit(10).
Random instances.RandomMap.put(i, new Random(i)); This will help you get back, your objects in this way > RandomMap.get(i);Stream.generate(Random::new).limit(10)When you have written this code.
for(int i = 0; i < 10; i++)
{
Random i = new Random();
}
You were thinking that multiple object of Random class will be created by the name 0,1,2,3,4.......9 but it does not work that way.
If you would have use something like this:-
for(int i = 0; i < 10; i++)
{
Random "obj"+i = new Random();
}
Then also it will not work.
If you have ever work with String class then you know that in order to create multiple object of String you need to do something like this.
String s1,s2,s3;
// and then
s1="first String ";
s2="second String";
s3="third String";//and so on
Similar think can be done with Random:-
Random r1,r2,r3;
r1=new Random();
r2=new Random();
r3=new Random();
But if you want to create many of them Array come into role.(Although there are other options also).
You can create array of any thing int,float ,String and objects of any class.
here is the syntax:-
<Classname> <variableName>[]=new <ClassName>[No of objects to be created];
Now For Random class you can do something like this.
Random ranList[]=new Random[10];
By writing this line you have just created a array of Random but not yet instantiated the object using new Keyword.
for that you have to do something like this.
for(int i = 0; i < 10; i++)
{
Random ranList[i] = new Random();
}
now you have 10 object of Random type each store at a different index of ranList variable.
ias two different things. Use a different variable name.