如何避免在增强型 for 循环之外声明变量

问题描述 投票:0回答:0

我想避免在增强型 for 循环之外使用变量 index,因为它在循环后毫无用处并污染命名空间,但无法找到解决方法。

问题

int index = 0;        // I want to avoid using this variable outside the loop
for (List<Integer> bucket : buckets) {
    for (int el : bucket) {
        a[index++] = el;
    }
}

完整代码

package sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class BucketSort {
    private BucketSort() {
    }

    private static int getMax(int[] a) {
        int max = Integer.MIN_VALUE;

        for (int el : a) {
            max = Math.max(max, el);
        }

        return max;
    }

    public static void sort(int[] a, int k) {
        int M = getMax(a) + 1;

        List<List<Integer>> buckets = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            buckets.add(new ArrayList<>());
        }

        for (int el : a) {
            int bucketIndex = (int) Math.floor(k * (double) el / M);
            buckets.get(bucketIndex).add(el);
        }

        for (List<Integer> bucket : buckets) {
            Collections.sort(bucket);
        }

        int index = 0;
        for (List<Integer> bucket : buckets) {
            for (int el : bucket) {
                a[index++] = el;
            }
        }
    }
}

一位用户提出了类似的问题,建议避免“无用变量”的一种方法是在整个区域周围包裹另一个块以进行局部作用域

{
    int index = 0;        
    for (List<Integer> bucket : buckets) {
        for (int el : bucket) {
            a[index++] = el;
        }
    }
}

但我不太确定。

java for-loop foreach scope
© www.soinside.com 2019 - 2024. All rights reserved.