重用代码循环遍历多维数组 [英] Reuse code for looping through multidimensional-array

查看:90
本文介绍了重用代码循环遍历多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个多维数组作为类的成员和许多方法,它们遍历数组的每个元素然后对其进行操作.代码可能看起来像这样:

Let's say I have a multi-dimensional array as a member of a class and a lot of methods, that loop through every element of the array and then operate on it. The code might look like this:

public class Baz {

    private Foo[][] fooArray = new Foo[100][100];

    public Baz() {
        for (int i = 0; i < fooArray.length; i++) {
            for (int j = 0; j < fooArray[i].length; j++) {
                // Initialize fooArray
            }
        }
    }

    public void method1() {
        for (int i = 0; i < fooArray.length; i++) {
            for (int j = 0; j < fooArray[i].length; j++) {
                // Do something with fooArray[i][j] 
            }
        }
    }

    public void method2() {
        for (int i = 0; i < fooArray.length; i++) {
            for (int j = 0; j < fooArray[i].length; j++) {
                // Do something else with fooArray[i][j] 
            }
        }
    }

    // and so on
}

现在,由于循环的代码始终是相同的,因此仅循环内的操作会发生变化,是否有任何方法可以将循环的代码重构为单独的方法?能够做到那真是太好了

Now, since the code for the loop is always the same, only the operation within the loop changes, is there any way the code for looping could be somehow refactored into a seperate method? It would be so nice to be able to do

doInLoop(functionToExecute());

如果可能的话,最能替代这种方法的东西是什么?

What would be the nearest substitute for doing something like this, if it is even possible?

推荐答案

您正在寻找的是 Command 模式:定义一个单方法接口,并针对每个用例将其实现为匿名方法班级.您将将此接口的实例传递给一个方法,该方法将完成所有样板操作,并仅针对有趣的部分调用您的方法:

What you are looking for is the Command pattern: define a single-method interface and implement it for each use case as an anonymous class. You'll pass an instance of this interface to a method which does all the boilerplate and calls your method just for the interesting part:

public void forAllMembers(Foo[][] fooArray, Command c) {
    for (int i = 0; i < fooArray.length; i++) {
        for (int j = 0; j < fooArray[i].length; j++) {
            c.execute(fooArray[i][j]);
        }
    }
}

或者,等待Java 8,它将引入Lambda,并将为您的问题提供一流的解决方案!

Or, wait for Java 8, which will introduce Lambdas and will give your problem a first-class solution!

这篇关于重用代码循环遍历多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆