增强FOR循环和数组复制
增强for:
package ArrDemo;
public class DemoStorngFOR {
//注:增强型for循环只能用来取值,却不能用来修改数组里的值
public static void main(String[] args) {
int i = 0;
int a [] = new int[]{18,61,22,63,25};
for(int each : a){
if(each>i){
i= each;
}
}
System.out.println("最大值是:"+i);//用增强型for循环找出最大的那个数
}
}
数组复制
package ArrDemo;
public class CopyArrDemo {
/*
把一个数组的值,复制到另一个数组中
System.arraycopy(src, srcPos, dest, destPos, length)
src: 源数组
srcPos: 从源数组复制数据的起始位置
dest: 目标数组
destPos: 复制到目标数组的起始位置
length: 复制的长度
*/
public static void main(String[] args) {
int num1 = (int) (Math.random() * 5 + 5);
int num2 = (int) (Math.random() * 5 + 5);
int a[] = new int[num1];
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * 100);
}//生成数组1
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
int b[] = new int[num2];
for (int i = 0; i < b.length; i++) {
b[i] = (int) (Math.random() * 100);
}//生成数组2
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
System.out.println();
int c[] = new int[num1 + num2];
//生成数组3
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
for (int i = 0; i < c.length; i++) {
System.out.print(c[i] + " ");
}
System.out.println();
}
}
文章展示了如何在Java中使用增强for循环遍历并处理数组,以及如何利用`System.arraycopy()`方法高效地复制数组。首先,通过一个例子解释了增强for循环不能修改数组元素的特性,并用其查找数组中的最大值。接着,文章详细演示了如何将两个随机生成的数组内容合并到一个新的数组中,利用了`System.arraycopy()`进行数组间的复制。
2476

被折叠的 条评论
为什么被折叠?



