Created
September 9, 2015 14:56
-
-
Save lukhnos/d6ec3723d3f370b3cf08 to your computer and use it in GitHub Desktop.
A case where you can't fast-enumerate an Iterable, 3/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 2: Use OCNI. | |
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; | |
} | |
}; | |
} | |
/*-[ | |
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { | |
// lorem ipsum | |
return JreDefaultFastEnumeration(self, state, stackbuf, 1); | |
} | |
]-*/ | |
} | |
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