Skip to content

Commit 18ce6a9

Browse files
committed
#63 Refactor for method foreach in ArrayList and add test case
1 parent c3f0722 commit 18ce6a9

2 files changed

Lines changed: 27 additions & 45 deletions

File tree

java/util/ArrayList/ArrayList.hpp

Lines changed: 11 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -47,45 +47,27 @@ using namespace Java::Util::Function;
4747

4848
namespace Java {
4949
namespace Util {
50-
template <typename E>
51-
class ArrayList;
52-
53-
template <typename E>
54-
class ArrayListIterator {
55-
public:
56-
ArrayListIterator(const ArrayList<E> *p_vec, int pos) : _pos(pos), _p_vec(p_vec) {
57-
58-
}
59-
60-
boolean operator!=(const ArrayListIterator<E> &other) const {
61-
return _pos != other._pos;
62-
}
63-
64-
int operator*() const {
65-
return _p_vec->get(_pos);
66-
}
67-
68-
const ArrayListIterator<E> &operator++() {
69-
++_pos;
70-
return *this;
71-
}
72-
73-
private:
74-
int _pos;
75-
const ArrayList<E> *_p_vec;
76-
};
7750
template <typename E>
7851
class ArrayList :
7952
public virtual AbstractList<E>,
8053
public virtual Serializable,
8154
public virtual Cloneable,
82-
// public virtual List<E>,
55+
// public virtual List<E>,
8356
public virtual RandomAccess {
8457
private:
8558
std::vector<E> original;
59+
typedef E* _iterator;
60+
typedef const E* _const_iterator;
61+
8662

8763
public:
88-
/**
64+
65+
_iterator begin() { return &this->original[0]; };
66+
_const_iterator begin() const { return &this->original[0]; };
67+
_iterator end() { return &this->original[this->original.size()]; };
68+
_const_iterator end() const { return &this->original[this->original.size()]; };
69+
70+
/**
8971
* Constructs an empty list
9072
*/
9173
ArrayList() {
@@ -117,22 +99,6 @@ namespace Java {
11799

118100
}
119101

120-
public:
121-
/**
122-
* @return
123-
*/
124-
ArrayListIterator<E> begin() const {
125-
return ArrayListIterator<E>(this, 0);
126-
}
127-
128-
/**
129-
*
130-
* @return
131-
*/
132-
ArrayListIterator<E> end() const {
133-
return original.end();
134-
}
135-
136102
public:
137103

138104
/**

java/util/ArrayList/ArrayListTest.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,19 @@ TEST(Javalang, ArrayListFunction) {
9595
ASSERT_EQUAL(0 ,intArray.get(-1));
9696
ASSERT_EQUAL(5 ,intArray.get(intArray.size()));
9797
}
98+
99+
TEST(JavaLang, ArrayListForEach) {
100+
//
101+
ArrayList<int> validArrayList;
102+
103+
int index;
104+
for (index = 0; index < 100; ++index) {
105+
validArrayList.add(index);
106+
}
107+
108+
int expect = 0;
109+
for (int element : validArrayList) {
110+
ASSERT_EQUAL(expect, element);
111+
expect++;
112+
}
113+
}

0 commit comments

Comments
 (0)