Skip to content

Commit da1c7d9

Browse files
committed
Iterator and forEach in HashSetCustom
1 parent c55b013 commit da1c7d9

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/Sets/HashSetCustom.java

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package Sets;
22

33
import java.util.*;
4+
import java.util.function.Consumer;
5+
46
import Maps.HashMapCustom;
57

6-
public class HashSetCustom<E> {
8+
public class HashSetCustom<E> implements Iterable<E> {
79

810
public HashSetCustom() {
911
}
@@ -36,4 +38,29 @@ public String toString() {
3638
return Arrays.toString(map.toKeyArray());
3739
}
3840

41+
public void forEach(Consumer<? super E> o) {
42+
map.forEach((k, v) -> {
43+
o.accept(k);
44+
});
45+
}
46+
47+
@Override
48+
public Iterator<E> iterator() {
49+
return new HashSetItr();
50+
}
51+
52+
private class HashSetItr implements Iterator<E> {
53+
private Object[] arr = map.toKeyArray();
54+
int cursor = 0;
55+
56+
@Override
57+
public boolean hasNext() {
58+
return cursor < arr.length;
59+
}
60+
61+
@Override
62+
public E next() {
63+
return (E) arr[cursor++];
64+
}
65+
}
3966
}

0 commit comments

Comments
 (0)