4.3 数组的引用传递
4.3.1 传递及返回数组
方法也可用来传递和返回数组。数组属于引用数据类型,所以把数组传递进方法之后,如果方法对数组做了任何修改,修改结果将保存下来
package com; public class ArrayRefDemo01 { public static void main(String[] args) { int temp[]={1,3,5}; fun(temp); for (int i=0;i<temp.length;i++){ System.out.print(temp[i]+"、"); } } public static void fun(int x[]){ x[0]=6; } }
6、3、5、 Process finished with exit code 0
将数组传递到方法中,使用数组x接收,也就是说此时temp实际上是将堆内存空间的使用权传递给了方法,为数组的具体内容起了别名x,然后在方法中通过x修改数组内容。方法执行完毕后,数组x因为是局部变量所以失效,但是对内容的修改保留下来,即引用传递
package com; public class ArrayRefDemo02 { public static void main(String[] args) { int temp[]=fun(); //通过方法实例化数组 print(temp); //向print()方法中传递数组 } public static void print(int x[]){ for (int i=0;i<x.length;i++){ System.out.print(x[i]+"、"); } } public static int[] fun() { //方法返回一个数组引用 int ss[]={1,3,5,7,9}; return ss; } }
1、3、5、7、9、 Process finished with exit code 0
4.3.2 范例——数组排序
package com; public class ArrayRefDemo03 { public static void main(String[] args) { int score[]={67,15,89,17,45}; int age[]={15,48,36,78,12}; bubbleSort(score); //数组排序 print(score); //数组打印 System.out.println(); System.out.println("————————————————————"); bubbleSort(age); //数组排序 print(age); //数组打印 } public static void bubbleSort(int temp[]){ for(int i=0;i<temp.length-1;i++){ for(int j=0;j<temp.length-1-i;j++){ if(temp[j]>temp[j+1]){ int middle=temp[j]; temp[j]=temp[j+1]; temp[j+1]=middle; } } } } public static void print(int temp[]){ for(int i=0;i<temp.length;i++){ System.out.print(temp[i]+"\t"); } } }
15 17 45 67 89 ———————————————————— 12 15 36 48 78 Process finished with exit code 0
对于排序操作,Java本身也有类库支持,可直接使用“java.util.Arrays.sort(数组名称)”对数组排序
package com; public class ArrayRefDemo04 { public static void main(String[] args) { int score[]={67,15,89,17,45}; int age[]={15,48,36,78,12}; java.util.Arrays.sort(score); //使用Java提供的排序操作 print(score); System.out.println(); System.out.println("————————————————————"); java.util.Arrays.sort(age); //使用Java提供的排序操作 print(age); } public static void print(int temp[]){ for(int i=0;i<temp.length;i++){ System.out.print(temp[i]+"\t"); } } }
15 17 45 67 89 ———————————————————— 12 15 36 48 78 Process finished with exit code 0
此方法可以直接对各个基本数据类型的数组进行排序,包括浮点型、字符型等
4.3.3 范例——数组复制
package com; public class ArrayCopyDemo01 { public static void main(String[] args) { int i1[]={1,2,3,4,5,6,7,8,9}; int i2[]={11,22,33,44,55,66,77,88,99}; copy(i1,3,i2,1,3); print(i2); } //参数含义: 原数组名称、原数组开始点、目标数组名称、目标数组开始点、复制长度 public static void copy(int s[],int s1,int o[],int s2,int len){ for (int i = 0; i < len; i++) { o[s2+i]=s[s1+i]; } } public static void print(int temp[]){ for (int i = 0; i < temp.length; i++) { System.out.print(temp[i]+"\t"); } } }
11 4 5 6 55 66 77 88 99 Process finished with exit code 0
对于复制操作,Java中也存在类库支持,直接使用System.arraycopy方法即可,此方法接收参数和以上copy()方法相同
Java中类库:Java提供大量类库,在java doc中可以查到