集合的遍历方法
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 () + "我是:" )
}