Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. package ca.ubc.cs.cpsc210.moreiterators;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5. import java.util.List;
  6.  
  7. /**
  8. * A collection-like class that stores its data in two separate lists
  9. *
  10. * Iterating over the data could return the data in a number of different ways:
  11. * 1) all the data from listone followed by all the data from listtwo
  12. * 2) the data from listone and listtwo alternating (one from listone, then
  13. * one from listtwo, then one from listone, ...). When one list runs out, then
  14. * return the rest of the data from the other list until it too runs out
  15. * 3) the data from the two lists combined (cartesian product style) by multiplying.
  16. * If there are three items in each list, named l11, l12, l13 and l21, l22, l23
  17. * This would be l11 * l21, l11 * l22, l11 * l23,
  18. * l12 * l21, l12 * l22, l12 * l23,
  19. * l13 * l21, l13 * l22, l13 * l23,
  20. */
  21. public class TwoLists implements Iterable<Integer>{
  22. private List<Integer> listone;
  23. private List<Integer> listtwo;
  24.  
  25. public TwoLists() {
  26. listone = new ArrayList<Integer>();
  27. listtwo = new ArrayList<Integer>();
  28. }
  29.  
  30. public void add(int which, Integer value) {
  31. switch (which) {
  32. case 1:
  33. listone.add(value);
  34. break;
  35. case 2:
  36. listtwo.add(value);
  37. break;
  38. }
  39. }
  40.  
  41. @Override
  42. public Iterator<Integer> iterator(){
  43. return new twoListIterator();
  44. }
  45.  
  46. private class twoListIterator implements Iterator<Integer>{
  47. int OIndex;
  48. int TIndex;
  49. boolean onFirst;
  50.  
  51. public twoListIterator(){
  52. OIndex = 0;
  53. TIndex = 0;
  54. onFirst = true;
  55. }
  56.  
  57. @Override
  58. public boolean hasNext(){
  59. if(OIndex < listone.size() && onFirst == true){
  60. return true;
  61. } else if( TIndex < listtwo.size() && onFirst == false){
  62. return true;
  63. } else
  64. return false;
  65.  
  66. }
  67.  
  68. @Override
  69. public Integer next(){
  70. if(onFirst){
  71. int next = OIndex;
  72. OIndex++;
  73. onFirst = false;
  74. return listone.get(next);
  75. } else {
  76. int next = TIndex;
  77. TIndex++;
  78. onFirst = true;
  79. return listtwo.get(next);
  80. }
  81. }
  82.  
  83. @Override
  84. public void remove(){
  85. throw new UnsupportedOperationException();
  86. }
  87.  
  88.  
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement