Posted on 2005-09-12 23:44
Justfly Shi 阅读(1644)
评论(0) 编辑 收藏 所属分类:
Study Tiger
改进的for循环是Java 5.0中的一个让我很喜欢的改进。它只对数组和实现了java.util.Iterable接口的容器类有效。
package cn.justfly.study.tiger.enhancedfor;
import java.util.ArrayList;
import java.util.Collection;
/**
* The demo of enhanced for statement
* it can only used for array and classes implements java.util.Iterable interface
* @author Justfly Shi
* created at 2005-8-28 21:42:12
*/
public class EnhancedFor {
/**
* @param args
*/
public static void main(String[] args) {
//for array
int[] intArray={1,2,3,4};
System.out.println("printing ints:");
for(int i:intArray){
System.out.println(i);
}
//for Collection
Collection<String> list=new ArrayList<String>();
for(int i=0;i<4;i++){
list.add("String"+i);
}
System.out.println("print Strings in an Collection:");
for(String i:list){
System.out.println(i);
}
//self-define Iterable
MyIterable<String> myIte=new MyIterable<String>(list);
System.out.println("print Stings in an Iterable");
for(String i:myIte){
System.out.println(i);
}
}
}
package cn.justfly.study.tiger.enhancedfor;
import java.util.Collection;
import java.util.Iterator;
/**
* an self-defined Iterable ,that can be used in enhanced-for statement
* @author Justfly Shi
* created at 2005-8-28 22:09:05
* @param
*/
public class MyIterable<G_E> implements Iterable<G_E> {
private Collection<G_E> _list;
public Iterator<G_E> iterator() {
return new MyIterator<G_E>(_list.iterator());
}
public MyIterable(Collection<G_E> list) {
_list = list;
}
class MyIterator<G_I> implements Iterator<G_I> {
private Iterator<G_I> _ite;
MyIterator(Iterator<G_I> ite) {
_ite = ite;
}
public boolean hasNext() {
return _ite.hasNext();
}
public G_I next() {
return _ite.next();
}
public void remove() {
_ite.remove();
}
}
}
输出结果
printing ints:
1
2
3
4
print Strings in an Collection:
String0
String1
String2
String3
print Stings in an Iterable
String0
String1
String2
String3