提供一种方法顺序访问一个容器对象中的各个元素,但又不暴露等于该对象的内部显示。
代码:list
<pre>
public interface BaseList<T> {
void add(T t);
void remove(T t);
Iterator<T> iterator();
}
public class BaseListImpl<T> implements BaseList<T> {
private List<T> list = new ArrayList<>();
@Override
public void add(T t) {
list.add(t);
}
@Override
public void remove(T t) {
list.remove(t);
}
@Override
public Iterator<T> iterator() {
return new ListIterator<>(list);
}
}
public interface Iterator<T> {
boolean hasNext();
T next();
}
public class ListIterator<T> implements Iterator<T> {
private List<T> list = new ArrayList<>();
private int cursor;
public ListIterator(List<T> list) {
this.list = list;
}
@Override
public boolean hasNext() {
return cursor != list.size();
}
@Override
public T next() {
T obj = null;
if (hasNext()) {
return list.get(cursor++);
}
return obj;
}
}
</pre>
代码:数组
<pre>
public interface BaseArray<T> {
void add(T t, int i);
void remove(int i);
Iterator<T> iterator();
}
public class BaseArrayImpl implements BaseArray<java.lang.String> {
private String[] array = new String[3];
@Override
public void add(java.lang.String t, int i) {
array[i] = t;
}
@Override
public void remove(int i) {
}
@Override
public Iterator<String> iterator() {
return new ArrayIterator(array);
}
}
public class ArrayIterator implements Iterator<String> {
private String[] array;
private int cursor;
public ArrayIterator(String[] array) {
this.array = array;
}
@Override
public boolean hasNext() {
return !(cursor > array.length - 1 || array[cursor] == null);
}
@Override
public String next() {
if (hasNext()) {
return array[cursor++];
}
return "";
}
}
</pre>
使用
<pre>
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BaseList<String> baseList = new BaseListImpl<>();
BaseArray<String> baseArray = new BaseArrayImpl();
baseList.add("一");
baseList.add("二");
baseList.add("三");
baseArray.add("1", 0);
baseArray.add("2", 1);
baseArray.add("3", 2);
Iterator<String> iterator = baseList.iterator();
Iterator<String> iterator2 = baseArray.iterator();
while (iterator.hasNext()) {
Log.i(TAG, "onCreate: " + iterator.next());
}
while (iterator2.hasNext()) {
Log.i(TAG, "onCreate: " + iterator2.next());
}
}
}
</pre>
log
<pre>
03-13 21:21:15.690 3290-3290/com.lerz.iteratordemo I/MainActivity: onCreate: 一
03-13 21:21:15.690 3290-3290/com.lerz.iteratordemo I/MainActivity: onCreate: 二
03-13 21:21:15.690 3290-3290/com.lerz.iteratordemo I/MainActivity: onCreate: 三
03-13 21:21:15.690 3290-3290/com.lerz.iteratordemo I/MainActivity: onCreate: 1
03-13 21:21:15.690 3290-3290/com.lerz.iteratordemo I/MainActivity: onCreate: 2
03-13 21:21:15.690 3290-3290/com.lerz.iteratordemo I/MainActivity: onCreate: 3
</pre>
网友评论