迭代匿名内部类java

时间:2018-04-11 08:33:03

标签: java

我有以下代码:

public void Or(BinaryMap source, RectangleC area, Point at) { 
  Combine(source, area, at, new CombineFunction() { 
   @Override
   public void combine(int[] target, int[] srcVector) { 
    for (int i = 0; i < target.length; ++i) 
     target[i] |= srcVector[i]; 
   } 
  });  
 } 

我无法理解接口CombineFunction实现是如何工作的,传递给函数组合的参数是保存在哪里的?

注意:

代码不是我的,它是这里的参考 https://www.programcreek.com/java-api-examples/index.php?source_dir=SecugenPlugin-master/src/sourceafis/simple/Fingerprint.java#

我只想了解它是如何运作的。

代码:

 interface CombineFunction { 
  void combine(int[] target, int[] source); 
 }

 void Combine(final BinaryMap source, final RectangleC area, final Point at, 
   final CombineFunction function) { 
  final int shift = (area.X & WordMask) - (at.X & WordMask); 
  int vectorSize = (area.Width >> WordShift) + 2; 
  CombineLocals combineLocals = new CombineLocals(); 
  combineLocals.Vector = new int[vectorSize]; 
  combineLocals.SrcVector = new int[vectorSize]; 
  ParallelForDelegate<CombineLocals> delegate = new ParallelForDelegate<CombineLocals>() { 
   @Override 
   public CombineLocals delegate(int y, CombineLocals locals) { 
    LoadLine(locals.Vector, new Point(at.X, at.Y + y), area.Width); 
    source.LoadLine(locals.SrcVector, 
      new Point(area.X, area.Y + y), area.Width); 
    if (shift >= 0) 
     ShiftLeft(locals.SrcVector, shift); 
    else 
     ShiftRight(locals.SrcVector, -shift); 
    function.combine(locals.Vector, locals.SrcVector); 
    SaveLine(locals.Vector, new Point(at.X, at.Y + y), area.Width); 
    return locals; 
   } 

   @Override 
   public CombineLocals combineResults(CombineLocals result1, 
     CombineLocals result2) { 
    return null; 
   } 
  }; 

 Parallel.For(0, area.Height, delegate, combineLocals); 
 } 

1 个答案:

答案 0 :(得分:1)

假设Combine是具有以下签名的方法:

private void Combine(BinaryMap bm, RectangleC rc, Point p, CombineFunction cf)

注意:正如Lutz Horn在评论中指出的那样,方法名称应以小写字母开头,因此它应为combine

<强>语法

写作

public void Or(BinaryMap source, RectangleC area, Point at) {
  Combine(source, area, at, new CombineFunction() {
    @Override
    public void combine(int[] target, int[] srcVector) {
      for (int i = 0; i < target.length; ++i)
        target[i] |= srcVector[i];
    }
  });
}

与写作相同

class MyCombineFunction implements CombineFunction {

  @Override
  public void combine(int[] target, int[] srcVector) {
    for (int i = 0; i < target.length; ++i)
      target[i] |= srcVector[i];
  }

}

然后以这种方式使用这个类:

public void Or(BinaryMap source, RectangleC area, Point at) {
    Combine(source, area, at, new MyCombineFunction());
}

这只是一个快捷方式,因此您无需申报新课程。

如何在Combine方法中使用

然后Combine方法使用您传递给它的MyCombineFunction自定义实现。 它会在执行期间以某种方式调用它的combine方法,如下所示:

private void Combine(BinaryMap bm, RectangleC rc, Point p, CombineFunction cf) {

    int[] target = ...;
    int[] src = ...
    cf.combine(target, source); // this will use the implementation you wrote when overriding the combine method
}