Created
September 9, 2015 14:55
-
-
Save lukhnos/1fadbde81e8d525c0a0b to your computer and use it in GitHub Desktop.
A case where you can't fast-enumerate an Iterable, 1/3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This works perfectly as a Java program, but produces wrong output when | |
// translated into Objective-C. Can you spot why? | |
import java.util.Arrays; | |
import java.util.Iterator; | |
import java.util.List; | |
public class FastEnumGotcha { | |
static class Wrapper<T> { | |
T value; | |
void set(T value) { | |
this.value = value; | |
} | |
T get() { | |
return value; | |
} | |
} | |
static class Data implements Iterable<Wrapper<String>> { | |
List<String> strings; | |
Data(String[] strings) { | |
this.strings = Arrays.asList(strings); | |
} | |
@Override | |
public Iterator<Wrapper<String>> iterator() { | |
return new Iterator<Wrapper<String>>() { | |
Wrapper<String> w = new Wrapper<>(); | |
Iterator<String> it = strings.iterator(); | |
@Override | |
public boolean hasNext() { | |
return it.hasNext(); | |
} | |
@Override | |
public void remove() { | |
throw new UnsupportedOperationException(); | |
} | |
@Override | |
public Wrapper<String> next() { | |
w.set(it.next()); | |
return w; | |
} | |
}; | |
} | |
} | |
public static void main(String args[]) { | |
String x[] = { | |
"alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", | |
"juliet", "kilo", "lima", "mike", "november", "oscar", "papa", "quebec", "romeo", | |
"sierra", "tango", "uniform", "victor", "whiskey", "x-ray", "yankee", "zulu" | |
}; | |
Data data = new Data(x); | |
for (Wrapper<String> w : data) { | |
System.out.printf("%s ", w.get()); | |
} | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment