当前位置:网站首页>实现接口 Interface Iterable<T>
实现接口 Interface Iterable<T>
2022-07-02 06:25:00 【霏霏小雨】
Java Doc
public interface Iterable
Implementing this interface allows an object to be the target of the enhanced for statement (sometimes called the “for-each loop” statement).
Since: 1.5
那么什么是 enhanced for statement 呢?查看 Java Language Specification,不做赘述,类似于下面的这种 for 语句。
for (T t : this)
action.accept(t);
那么我们要实现接口,具体需要实现什么方法函数呢?没错,就是Iterator<T> iterator()
这个方法。这一方法,Returns an iterator over elements of type T.
实现这一方法,需要返回一个Iterator<T>
的对象,Iterator<T>
同样是一个接口,我们创建一个相应的对象,就需要先实现这个接口类。这个接口类需要实现的方法有:
boolean hasNext();
Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)
T next();
Returns the next element in the iteration.
根据这些已知,我们就可以开始实现这个接口了。
完整代码
import java.util.Arrays;
import java.util.Iterator;
public class ImplementIterable implements Iterable<String> {
private int size;
private int current;
private Object [] o;
ImplementIterable() {
size = 0;
o = new Object [1];
}
public void add(String s) {
if(size == o.length) {
o= Arrays.copyOf(o, o.length<<1);
}
o[size ++] = s;
}
@Override
public Iterator<String> iterator() {
class I implements Iterator<String> {
I() {
current = 0;
}
@Override
public boolean hasNext() {
if(current < size) {
return true;
}
return false;
}
@Override
public String next() {
return o[current ++].toString();
}
}
return new I();
}
public static void main(String[] args) {
ImplementIterable i = new ImplementIterable();
i.add("a");
i.add("b");
i.add("c");
for(String s : i) {
System.out.println(s);
}
}
}
边栏推荐
- SQLI-LABS通關(less6-less14)
- SQLI-LABS通关(less6-less14)
- Oracle 11.2.0.3 handles the problem of continuous growth of sysaux table space without downtime
- Pyspark build temporary report error
- Sqli-labs customs clearance (less18-less20)
- oracle-外币记账时总账余额表gl_balance变化(上)
- php中根据数字月份返回月份的英文缩写
- Explain in detail the process of realizing Chinese text classification by CNN
- TCP attack
- Uniapp introduces local fonts
猜你喜欢
随机推荐
view的绘制机制(三)
UEditor . Net version arbitrary file upload vulnerability recurrence
Error in running test pyspark in idea2020
Oracle 11g uses ords+pljson to implement JSON_ Table effect
解决万恶的open failed: ENOENT (No such file or directory)/(Operation not permitted)
php中获取汉字拼音大写首字母
Pyspark build temporary report error
在php的开发环境中如何调取WebService?
IDEA2020中PySpark的两表关联(字段名相同)
Data warehouse model fact table model design
The boss said: whoever wants to use double to define the amount of goods, just pack up and go
SSM实验室设备管理
oracle apex ajax process + dy 校验
2021-07-05c /cad secondary development create arc (4)
SQLI-LABS通关(less1)
In depth study of JVM bottom layer (V): class loading mechanism
Check log4j problems using stain analysis
搭建frp进行内网穿透
Sqli-labs customs clearance (less2-less5)
MapReduce concepts and cases (Shang Silicon Valley Learning Notes)