Created
November 17, 2013 07:14
-
-
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.
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
/** | |
* | |
*/ | |
/** | |
* 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); | |
} | |
} | |
} |
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
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