如果我不知道未来的大小,如何在 Java 中连接两个以上的整数数组?



我正在Java上做功课,我必须将字符串转换为char数组,然后在整数数组上,之后,整数数组的每个位置都必须转换为二进制,因此由于二进制比十进制上的相同数字长,我必须知道长度将如何使我未来的整数数组与二进制数一起做我在互联网上看到的所有示例, 如果您有其他解决方案,请您对我有很大帮助

例如

int[] a={1,1,0};
int[] b={1,1,0,0};
int[] c={1,0,1,0,1};
int[] result={1,1,0,1,1,0,0,1,0,1,0,1}; // a+b+c

对于您的特定示例,您只需将abc的长度相加即可获得最终的数组大小并使用System.arraycopy来合并它们。演示:https://ideone.com/D2EW2Q

int[] a = { 1, 1, 0 };
int[] b = { 1, 1, 0, 0 };
int[] c = { 1, 0, 1, 0, 1 };
final int[] result = new int[a.length + b.length + c.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
System.arraycopy(c, 0, result, a.length + b.length, c.length);
System.out.println(Arrays.toString(result));

对于更通用的方法,可以使用流。演示:https://ideone.com/fZhgls

public static void main(final String[] args) {
int[] a = { 1, 1, 0 };
int[] b = { 1, 1, 0, 0 };
int[] c = { 1, 0, 1, 0, 1 };
final int[] merged = merge(a, b, c);
System.out.println(Arrays.toString(merged));
}
public static int[] merge(final int[]... arrs) {
return Arrays.stream(arrs).flatMapToInt(IntStream::of).toArray();
}

最新更新