我已经使用其他成员给我的想法然后更改了几个容器来汇总下面的代码.对于我的生活,我真的无法理解其中的一些.代码的原因是我希望将函数作为参数传递.我特别不理解的代码部分是:
doFunc(numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
System.out.println(anInt);
}
});
Run Code Online (Sandbox Code Playgroud)
我在某种程度上理解我们正在使用一个接口来表示一个使用对象的函数(我认为?).这是完整的代码:
public static void main(String[] args) {
Integer[] strArray = new Integer[]{1,2,3,4,5};
List numbers = Arrays.asList(strArray);
doFunc(numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
System.out.println(anInt);
}
});
for(int y =0; y<numbers.size();y++){
System.out.println(numbers.get(y));
}
}
public static void doFunc(List c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
public interface IFunction {
public void execute(Object o);
}
Run Code Online (Sandbox Code Playgroud)
我想我只需要有人慢一点解释它.谢谢你的支持.
这是一个匿名的内部阶级.你可以做到如下:
public static void main(String[] args) {
Integer[] strArray = new Integer[]{1,2,3,4,5};
List numbers = Arrays.asList(strArray);
doFunc(numbers, new ConcreteFunction());
for(int y =0; y<numbers.size();y++){
System.out.println(numbers.get(y));
}
}
public static void doFunc(List c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
public interface IFunction {
public void execute(Object o);
}
public class ConcreteFunction implements IFunction {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
System.out.println(anInt);
}
}
Run Code Online (Sandbox Code Playgroud)
不同之处在于具体类是可重用的,而匿名内部类则不可重用.
| 归档时间: |
|
| 查看次数: |
1417 次 |
| 最近记录: |