集合的遍历方法
List<String>
list = new ArrayList<String>();
list.add(
"aaa");
list.add(
"bbb");
list.add(
"ccc");
方法一:
超级
for循环遍历
for(String attribute :
list) {
System.out.println(attribute);
}
方法二:
对于ArrayList来说速度比较快, 用
for循环, 以size为条件遍历:
for(int i =
0 ; i <
list.size() ; i++) {
system.out.println(
list.
get(i));
}
方法三:
集合类的通用遍历方式, 从很早的版本就有, 用迭代器迭代
Iterator
it =
list.iterator();
while(
it.hasNext()) {
System.ou.println(
it.next);
}
设计自己的Iterator迭代器
设计自己的迭代器接口功能包括哪些功能
/**
* Created by shiqiang on 2016/12/22.
*/
public interface Iterator {
Object previous();
Object next();
boolean hasNext();
Object first();
}
实现该接口的迭代器
/**
* Created by shiqiang on 2016/12/22.
*/
public class MyIterator implements Iterator {
private MyCollection myCollection;
private int pos = -
1;
public MyIterator(MyCollection myCollection) {
this.myCollection = myCollection;
}
@Override
public Object
previous() {
if (pos >
0){
pos -- ;
}
return myCollection.get(pos);
}
@Override
public Object
next() {
if (pos < myCollection.size() -
1){
pos ++ ;
}
return myCollection.get(pos);
}
@Override
public boolean hasNext() {
if (pos < myCollection.size() -
1){
return true ;
}
else{
return false ;
}
}
@Override
public Object
first() {
pos =
0 ;
return myCollection.get(pos);
}
}
集合的接口:注意需要哪些数据,在MyIterator中需要 myCollection.get(pos),myCollection.size() ,所以接口中应该此方法
/**
* Created by shiqiang on 2016/12/22.
*/
public interface Collection {
public Iterator
iterator();
public Object
get(
int i);
public int size();
}
实现该接口的集合
/**
* Created by shiqiang on 2016/12/22.
*/
public class MyCollection implements Collection {
public String string[] = {
"A",
"B",
"C",
"D",
"E"};
@Override
public Iterator
iterator() {
return new MyIterator(
this);
}
@Override
public Object
get(
int i) {
return string[i];
}
@Override
public int size() {
return string.length;
}
}
调用自己的集合跟迭代器遍历集合取出数据
MyCollection myCollection = new MyCollection()
//初始化自己的iterator,注意myCollection
.iterator()返回的是 return new //MyIterator(this)
Iterator iterator = myCollection
.iterator()
// System
.out.println(iterator
.first()
.toString() +
"nimei")
while (iterator
.hasNext()){
System
.out.println(iterator
.next() +
"我是:")
}
转载请注明原文地址: https://ju.6miu.com/read-40095.html