Posted By

Cano0617 on 12/08/12


Tagged


Versions (?)

FunkyList


 / Published in: Java
 

Funky

  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Iterator;
  4. import java.util.Random;
  5. /**
  6.  *
  7.  * @author wuaddiso
  8.  */
  9. public class FunkyList<K> implements Iterable<K> {
  10.  
  11. ArrayList<K> array = new ArrayList<K>();
  12.  
  13. public void add(K item){
  14. array.add(item);
  15. Collections.shuffle(array);
  16. }
  17.  
  18. public K remove(){
  19. return array.remove(0);
  20. }
  21.  
  22. public Iterator<K> iterator() {
  23. return new FunkyIterator();
  24. }
  25.  
  26. private class FunkyIterator implements Iterator<K>{
  27. Random generator = new Random();
  28. ArrayList<Integer> history = new ArrayList<Integer>();
  29. public boolean hasNext() {
  30. return (history.size()<array.size());
  31. }
  32.  
  33. public K next() {
  34. if(history.size()==array.size())
  35. //if all indices have been used
  36. history.clear();
  37. int index = generator.nextInt(array.size());
  38. while(history.contains(index)){
  39. //if (index has been used before)
  40. //generate new index
  41. index = generator.nextInt(array.size());
  42. }
  43. history.add(index);
  44. return array.get(index);
  45.  
  46. }
  47.  
  48. public void remove() {
  49. throw new UnsupportedOperationException("Not supported yet.");
  50. }
  51.  
  52. }
  53. }

Report this snippet  

You need to login to post a comment.