You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组长度不同时,除循环外是否有更优的双数组并排打印方法?

Great question! The approach you mentioned works, but we can make the code cleaner, more maintainable, and avoid splitting the logic into multiple loops. Here are a couple of more elegant solutions:

1. Use a Helper Method with a Single Loop

This approach reduces code duplication by extracting the "get element or default" logic into a reusable method, then iterating over the maximum length of the two arrays once:

public class ArrayPairPrinter {
    // Helper method to safely get an element or return "--" if index is out of bounds
    private static String getElementOrDefault(String[] array, int index) {
        return index < array.length ? array[index] : "--";
    }

    public static void main(String[] args) {
        String[] names = {"Sam", "Ben", "Nancy"};
        String[] ages = {"5", "10"};
        
        int maxLength = Math.max(names.length, ages.length);
        
        // Single loop handles all elements, no need for separate logic for remaining items
        for (int i = 0; i < maxLength; i++) {
            System.out.printf("%s %s%n", getElementOrDefault(names, i), getElementOrDefault(ages, i));
        }
    }
}

2. Functional Approach with Java Streams (Java 8+)

If you prefer a more concise, declarative style, you can use IntStream to iterate over the indices:

import java.util.stream.IntStream;

public class ArrayPairPrinter {
    private static String getElementOrDefault(String[] array, int index) {
        return index < array.length ? array[index] : "--";
    }

    public static void main(String[] args) {
        String[] names = {"Sam", "Ben", "Nancy"};
        String[] ages = {"5", "10"};
        
        int maxLength = Math.max(names.length, ages.length);
        
        IntStream.range(0, maxLength)
                 .forEach(i -> System.out.printf("%s %s%n",
                     getElementOrDefault(names, i),
                     getElementOrDefault(ages, i)));
    }
}

Why These Are Better

  • Single loop/stream: No need to split the logic into two separate parts (handling the shorter array, then the remaining elements), which reduces code duplication and potential bugs.
  • Reusable helper method: If you need to handle more arrays later, you can easily reuse the getElementOrDefault method instead of rewriting the ternary condition every time.
  • Readability: The intent of the code is clearer at a glance—we're pairing elements from both arrays, using "--" as a fallback when one array runs out of elements.

内容的提问来源于stack exchange,提问作者riorio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:39:05