I am trying to use an integer array. Now, there are a couple of things;
- I cannot initialize the size during initialization as it depends on some other condition (can be 1,2,5 elements, etc)
- I want to iterate over it & perform some operation. However, I do know for sure those would be integer elements always
So, my question is how can I initialize the array in this case ?
int[] dynamicSizeArr = new int[0];
switch (someVar) {
case "A":
dynamicSizeArr = new int[] { 5,10,15,20,25};
break;
case "B":
dynamicSizeArr = new int[] { 10,20};
break;
case "C":
dynamicSizeArr = new int[] { 10};
break;
default:
break;
}
for (int i = 0; i < dynamicSizeArr.length; i++) {
x.insert(dynamicSizeArr[i] + i, '.');
}
int[] dynamicSizeArr = null;but the OP code should workArrayListis the standard way to have a dynamically sized array in Java. By definition, using a primitive array in this way is unusual. However, it's not wrong. If yourswitchwere in a method that you call, then it wouldn't even be that unusual.