Created
September 9, 2015 14:56
-
-
Save lukhnos/e79d267528a3f85d7b96 to your computer and use it in GitHub Desktop.
A case where you can't fast-enumerate an Iterable, 2/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
// Solution 1: Use annotation. | |
import com.google.j2objc.annotations.LoopTranslation; | |
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 (@LoopTranslation(LoopTranslation.LoopStyle.JAVA_ITERATOR) 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