It's unclear what you're trying to achieve. An enhanced for loop can only iterate over a collection - in your case, you don't have useful values in a collection to start with - only a collection you're trying to populate.
If you're just trying to populate one array based on some calculation which isn't based on an existing collection, an enhanced for loop isn't helpful.
Even if you do want to populate the array based on another collection, using an enhanced for loop isn't ideal, as you don't have any concept of an index. For example, if you have a String
array and you want to populate an int
array with the lengths of the strings, you can do:
String[] words = ...; // Populate the array
int[] lengths = new int[words.length];
int index = 0;
for (String word : words) {
lengths[index++] = word.length();
}
... but it's not ideal. It's better if you're populating a List
of course, as then you can just call add
:
String[] words = ...; // Populate the array
List<Integer> lengths = new ArrayList<Integer>(words.length);
for (String word : words) {
lengths.add(word.length());
}