Skip to content

Instantly share code, notes, and snippets.

@alexvbush
Created November 17, 2013 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexvbush/7510370 to your computer and use it in GitHub Desktop.
Save alexvbush/7510370 to your computer and use it in GitHub Desktop.
An example of a custom collection class that you can use to iterate over your own collection object using for_each loop. The key ingredient is Iterable, and Iterator interfaces implemented in CustomCollectionWrapper class.
/**
*
*/
/**
* Smart Cloud, Inc. Nov 14, 2013.
* @author Alex Bush
*
*/
public class CollectionTest {
/**
* @param args
*/
public static void main(String[] args) {
CustomCollectionWrapper collectionWrapper = new CustomCollectionWrapper();
Object obj1 = new Object();
Object obj2 = new Object();
Object obj3 = new Object();
System.out.println("obj1= " + obj1);
System.out.println("obj2= " + obj2);
System.out.println("obj3= " + obj3);
collectionWrapper.add("one", obj1);
collectionWrapper.add("two", obj2);
collectionWrapper.add("three", obj3);
System.out.println("\nIterating over our collection\n");
for (String key : collectionWrapper) {
Object obj = collectionWrapper.get(key);
System.out.println("obj = " + obj + " for key: " + key);
}
}
}
import java.util.HashMap;
import java.util.Iterator;
/**
*
*/
/**
* Smart Cloud, Inc. Nov 14, 2013.
* @author Alex Bush
*
*/
public class CustomCollectionWrapper implements Iterable<String>, Iterator<String> {
private HashMap<String, Object> internalStorage = new HashMap<String, Object>();
private int count = 0;
public void add(String key, Object value) {
internalStorage.put(key, value);
}
public Object get(String key) {
return internalStorage.get(key);
}
@Override
public boolean hasNext() {
if (count < internalStorage.size()) {
return true;
}
return false;
}
@Override
public String next() {
if (count == internalStorage.size()) throw new IndexOutOfBoundsException();
count++;
return (String) internalStorage.keySet().toArray()[count - 1];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterator<String> iterator() {
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment