0

I am trying to use an integer array. Now, there are a couple of things;

  1. I cannot initialize the size during initialization as it depends on some other condition (can be 1,2,5 elements, etc)
  2. 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, '.');
}
6
  • 1
    What's wrong with your posted code? Commented Nov 21, 2019 at 4:54
  • 3
    Personally I would do int[] dynamicSizeArr = null; but the OP code should work Commented Nov 21, 2019 at 4:57
  • @ElliottFrisch; I have initialized it with size 0 (new int[0])...I am not sure if that is standard and then I keep on assigning it dynamically like dynamicSizeArr = new int[] { 10,20}, etc Commented Nov 21, 2019 at 5:00
  • 1
    ArrayList is 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 your switch were in a method that you call, then it wouldn't even be that unusual. Commented Nov 21, 2019 at 5:03
  • I would say initializing int[] dynamicSizeArr = {}; would be more natural. Commented Nov 21, 2019 at 5:27

1 Answer 1

3

Use java.util.ArrayList in that case.

ArrayList<Integer> arr = new ArrayList<Integer>();
int n = 5;
//n can be anything
for (int i=0; i<n; i++) 
       arr.add(i); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.