Razor1692 Razor1692 -4 years ago 89
Java Question

How create an array in run time in java?

**I want to know how to create an array in run time in java? For an instance say that i want to check the numbers which divides 498 ,and i want to put them into an array ?

for(i=1;i<=498/2;i++){
int z=498%i;
if(z==o)// put the i into the array if not continue

Answer Source

you can create an ArrayList while iterating for loop and later you can convert it to Array like below if you need an array at the end of process

integer [] myNumbers = list.toArray(new Integer[list.size()]);

this will help you not worrying about re sizing of Array at runtime

so finally your code should look like following

List<Integer> numbers = new ArrayList<Integer>();
for(i=1;i<=498/2;i++){
   int z=498%i;
   if(z==o){
     numbers.add(i);
   }
}

int [] myNumbers = numbers.toArray(new Integer[numbers.size()]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download