Skip to content

Commit 927209c

Browse files
author
Eugene Karpenko
committed
added iterator for improved array
1 parent 3bd74c8 commit 927209c

File tree

3 files changed

+42
-4
lines changed

3 files changed

+42
-4
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.hillel.java.dataStructures;
2+
3+
import com.hillel.java.dataStructures.arrayList.ImprovedArray;
4+
5+
import java.util.Iterator;
6+
7+
/**
8+
* Created by Eugene Karpenko on 25.04.2015.
9+
*/
10+
public class ArrayIterator implements Iterator {
11+
private int pointer;
12+
private IDataStructure dataStructure;
13+
14+
public ArrayIterator(IDataStructure dataStructure) {
15+
this.dataStructure = dataStructure;
16+
}
17+
18+
@Override
19+
public boolean hasNext() {
20+
return pointer < dataStructure.size();
21+
}
22+
23+
@Override
24+
public Object next() {
25+
return dataStructure.get(pointer++);
26+
}
27+
}

src/com/hillel/java/dataStructures/arrayList/ImprovedArray.java

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
package com.hillel.java.dataStructures.arrayList;
22

3+
import com.hillel.java.dataStructures.ArrayIterator;
34
import com.hillel.java.dataStructures.IDataStructure;
45

56
import java.util.Arrays;
7+
import java.util.Iterator;
68

79
/**
810
* Created by EKarpenko on 15.04.2015.
911
*/
10-
public class ImprovedArray implements IDataStructure {
12+
public class ImprovedArray implements IDataStructure, Iterable {
1113
private Object[] array = new Object[10];
1214
private int arrayCounter = 0;
1315

@@ -86,10 +88,10 @@ public boolean equals(Object other) {
8688

8789
public String toString() {
8890
String string = "[";
89-
for (int i = 0; i < array.length; i++)
91+
for (int i = 0; i < size(); i++)
9092
{
91-
string += array[i] != null ? array[i] : " ";
92-
string += (i < array.length - 1 ? ", " : "");
93+
string += get(i) != null ? get(i).toString() : " ";
94+
string += (i < size() - 1 ? ", " : "");
9395
}
9496
string += "]";
9597
return string;
@@ -100,4 +102,9 @@ private void resize() {
100102
array = Arrays.copyOf(array, array.length * 2);
101103
}
102104
}
105+
106+
@Override
107+
public Iterator iterator() {
108+
return new ArrayIterator(this);
109+
}
103110
}

test/ImprovedArrayTest.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,5 +44,9 @@ public void arrTest() {
4444
//Assert.assertEquals(null, improvedArray.get(55));
4545
Assert.assertEquals(12, improvedArray.size());
4646
Assert.assertTrue("arrays equal", improvedArray2.equals(improvedArray));
47+
48+
for (Object num:improvedArray) {
49+
System.out.println(num);
50+
}
4751
}
4852
}

0 commit comments

Comments
 (0)