数组长度不同时,除循环外是否有更优的双数组并排打印方法?
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
getElementOrDefaultmethod 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
相关产品推荐
相关产品推荐

