1

I want to achieve this:

int item1, item2, item3;
for (i = 0; i < size; i++) {
  "item"+i = i;
}

How would I do this? I want to get the variable name there but it would be a combination of something that doesn't work (string+integer) instead of the variable name

  • Java is both statically typed and has static variable names. Short answer: NO, you can not do that. – DwB Dec 04 '13 at 21:43
  • arrays are your friend! – ryrich Dec 04 '13 at 21:44
  • Arrays are the best option, but if you're using individual fields which have already been created (no dynamic creation in Java) you can check out [Reflection](http://docs.oracle.com/javase/tutorial/reflect/index.html). Kind of ambitious and unnecessary for this purpose, though. – Reinstate Monica -- notmaynard Dec 04 '13 at 22:10

2 Answers2

7

You need an array for this, instead of various similarly named variables.

int[] item = new int[3];
for (int i = 0; i < 3; i++) {
    item[i] = i;
}
rgettman
  • 176,041
  • 30
  • 275
  • 357
2

As an alternative to rgettman's answer, you could also use a Map to stick with your strings.

Map<String, Integer> data = new HashMap<String, Integer>();
for(int i = 0;i < 3;i ++){
    data.put("item" + i, i);
}

Although this may be a tad overkill.

As per Flight Odyssey's comment, you can then retrieve data with:

data.get("item"+i).intValue();

Although the .intValue() is optional in some cases due to unboxing.

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45