java - 用 Java 中的循环替换代码中的语句

标签 java arrays performance loops iteration

我有这两段代码:

    int prevY = 0;
    // this is the function InsertionSort applied to i
    StdDraw.setPenColor(Color.blue);
    for (int i = 1; i <= N; i++) {
        int x = i;
        int y = runInsertion(i);
        int prevX = i - 1;
        StdDraw.setPenRadius(lineRadius);
        StdDraw.line(prevX, prevY, x, y);
        StdDraw.setPenRadius(pointRadius);
        StdDraw.point(x, y);
        prevY = y;
    }

    prevY = 0;
    // this is the function SelectionSort applied to i
    StdDraw.setPenColor(Color.black);
    for (int i = 1; i <= N; i++) {
        int x = i;
        int y = runSelection(i);
        int prevX = i - 1;
        StdDraw.setPenRadius(lineRadius);
        StdDraw.line(prevX, prevY, x, y);
        StdDraw.setPenRadius(pointRadius);
        StdDraw.point(x, y);
        prevY = y;
    }

除了所使用的颜色和所使用的排序算法略有变化之外,它们都执行相同的操作。

有没有办法为颜色和排序算法创建一个数组,例如:

String[] algorithms = {"runInsertion", "runSelection"}
String[] colors = {"blue", "black"};

然后用for循环调用适当的索引,这样代码就被缩短了。

我知道这不会像我提议的那样起作用,但我只是想知道是否有某种方式或特定方法可以让我做到这一点。

最佳答案

只需将逻辑提取到具有所需参数的方法中即可:

void work(Color color, Function<Integer, Integer> algorithm) {
    int prevY = 0;
    StdDraw.setPenColor(color);
    for (int i = 1; i <= N; i++) {
        int x = i;
        int y = algorithm.apply(i);
        int prevX = i - 1;
        StdDraw.setPenRadius(lineRadius);
        StdDraw.line(prevX, prevY, x, y);
        StdDraw.setPenRadius(pointRadius);
        StdDraw.point(x, y);
        prevY = y;
    }
}

并调用它:

work(Color.blue, this::runInsertion);
work(Color.black, this::runSelection);

或者对于数组:

List<Function<Integer, Integer>> algorithms = Arrays.asList(this::runInsertion, this::runSelection);
List<Color> colors = Arrays.asList(Color.blue, Color.black);

for (int i = 0; i < algorithms.size(); i++) {
    work(colors.get(i), algorithms.get(i));
}

关于java - 用 Java 中的循环替换代码中的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800700/

相关文章:

c - 从两个数组中输出不同的元素

php - 获取最大值PHP 中 3D 数组的索引

c - C中字母表排序组合的多线程计算

c++ - C++ 是否允许 VLA 作为函数参数

java - 使用较新的类从磁盘读取序列化的 java 对象?

java - 使用递归返回最小值和最大值及其在数组列表中的位置

java - 在sql语句中使用java变量

performance - DirectX9 - 高效绘制 Sprite

c# - 多余的强制转换会影响性能吗?

java - Cassandra 抛出 OutOfMemory ;怎么调?