Trinh Tong 6 lat temu
rodzic
commit
4030a3277b
2 zmienionych plików z 58 dodań i 2 usunięć
  1. 36
    1
      src/main/java/MySet.java
  2. 22
    1
      src/test/java/MySetTest.java

+ 36
- 1
src/main/java/MySet.java Wyświetl plik

@@ -1,4 +1,6 @@
1
-public class MySet<T> extends MyArrayList<T> {
1
+import java.util.Iterator;
2
+
3
+public class MySet<T> extends MyArrayList<T> implements Iterable<T> {
2 4
 
3 5
     public MySet() {
4 6
 
@@ -24,7 +26,40 @@ public class MySet<T> extends MyArrayList<T> {
24 26
             setMyArrayList(tempArray1);
25 27
             setSize(getSize() + 1);
26 28
 
29
+        }
30
+    }
31
+
32
+    public class SetIterator implements Iterator<T> {
33
+        int current = 0;
34
+
35
+        public boolean hasNext() {
36
+            if (current < getSize()) {
37
+                return true;
38
+            }
39
+            return false;
40
+        }
41
+
42
+        @Override
43
+        public T next() {
44
+            if (!hasNext()) {
45
+                throw new ArrayIndexOutOfBoundsException();
46
+            }
47
+
48
+            return (T) getMyArrayList()[current++];
49
+        }
50
+
51
+        @Override
52
+        public void remove() {
53
+        // removes current -1
54
+            if (current < getSize() - 1) {
55
+                MySet.this.remove(next());
56
+            }
27 57
 
28 58
         }
29 59
     }
60
+
61
+    @Override
62
+    public Iterator<T> iterator() {
63
+        return new SetIterator();
64
+    }
30 65
 }

+ 22
- 1
src/test/java/MySetTest.java Wyświetl plik

@@ -30,5 +30,26 @@ public class MySetTest {
30 30
         Assert.assertEquals(expectedSize, mySet.getSize());
31 31
     }
32 32
 
33
-    
33
+    @Test
34
+    public void testContainsTrue() {
35
+
36
+        mySet.add(1);
37
+        mySet.add(2);
38
+        mySet.add(5);
39
+        mySet.add(10);
40
+
41
+        Assert.assertTrue(mySet.contains(2));
42
+    }
43
+
44
+    @Test
45
+    public void testContainsFalse() {
46
+        mySet.add(1);
47
+        mySet.add(2);
48
+        mySet.add(5);
49
+        mySet.add(10);
50
+
51
+        Assert.assertFalse(mySet.contains(3));
52
+    }
53
+
54
+
34 55
 }