-1

I´m struggling with making enhanced for loop from this regular for loop. I want each element of my String ArrayList to be equal to its value + " done"

for (int i = 0; i < stringList.size(); i ++)
{
    stringList.set(i, stringList.get(i) + " done");
}

Thank you for helping me.

Smittey
  • 2,475
  • 10
  • 28
  • 35
  • 1
    Possible duplicate of [What is the syntax of enhanced for loop in Java?](https://stackoverflow.com/questions/11685305/what-is-the-syntax-of-enhanced-for-loop-in-java) – OH GOD SPIDERS Dec 05 '17 at 10:46
  • 1
    You can't/shouldn't replace the value in a specific position with it. If you only do a `List.get`, this is fine, but `List.set` is a problem. – AxelH Dec 05 '17 at 10:46
  • 2
    ***Why*** do you want to replace the code above with an enhanced `for`? – T.J. Crowder Dec 05 '17 at 10:50
  • 1
    @T.J.Crowder is right here, classic example of XY problem... – nafas Dec 05 '17 at 10:51

2 Answers2

3

You can't use an enhanced for loop for this.

Either continue to use your existing code (which is fine for a RandomAccess list), or use List.replaceAll:

stringList.replaceAll(s -> s + " done");

Or, if you're still stuck on a pre-Java 8 version, use the code in the Java 8 Javadoc:

 final ListIterator<String> li = stringList.listIterator();
 while (li.hasNext()) {
     li.set(li.next() + " done");
 }
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

You can replace it with an enhanced for, but it's not really a good use of it:

int i = 0;
for (String s : stringList)
{
    stringList.set(i++, s + " done");
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875