11 --> java 数组的引用传递

来源:互联网 发布:知乎专栏怎么样 编辑:程序博客网 时间:2024/06/11 07:04
1、向方法中传递数组

//范例方法中传递数组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] + "\t");}}public static void fun(int x[]) {//接收整型数组引用x[0] = 6;//修改第一个元素的内容x[1] = 7;//修改第二个元素的内容}}

程序运行结果:

675

2、使用方法返回一个数组

//使用方法返回一个数组public class ArrayRefDemo02 {public static void main(String[] args) {int temp[] = fun();//通过方法实例化数组print(temp);//向print()方法中传递数组}public static int[] fun() {//此方法返回一个数组引用int ss[] = {1,3,5,7,9};//定义一个数组return ss;//返回数组}public static void print(int a[]) {//接收数组,循环输出for(int i = 0; i < a.length; i++){//循环输出System.out.print(a[i] + "\t");}}}

程序运行结果:

13579

3、将数组排序程序修改成一个方法的调用形式

//将数组排序程序修改成一个方法的调用形式public class ArrayRefDemo {public static void main(String[] args) {int score[] = { 85, 66, 95, 43, 21, 97, 86, 52 }; // 定义整型数组int age[] = { 13, 25, 16, 7, 9, 12, 11, 26 }; // 定义整型数组sort(score); // 数组排序print(score); // 数组打印System.out.println("\n----------------------------------------------------------------");sort(age); // 数组排序print(age); // 数组打印}public static void sort(int temp[]) { // //数组打印for (int i = 1; i < temp.length; i++) { // 使用冒泡算法排序for (int j = 0; j < temp.length; j++) {if (temp[i] < temp[j]) {int x = temp[i]; // 交换位置操作temp[i] = temp[j];temp[j] = x;}}}}public static void print(int temp[]) { // 输出数组内容for (int i = 0; i < temp.length; i++) {System.out.print(temp[i] + "\t");}}}

程序运行结果:

2143526685869597----------------------------------------------------------------79111213162526

4、使用java类库完成数组的排序操作

//使用java类库完成数组的排序操作public class ArrayRefDemo01 {public static void main(String[] args) {int score[] = { 55, 44, 66, 22, 88, 77, 33, 11, 99 };int age[] = { 5, 4, 6, 2, 8, 7, 3, 1, 9 };java.util.Arrays.sort(score); // 使用java提供的排序操作print(score);System.out.println("\n--------------------------------------------------------------------");java.util.Arrays.sort(age);print(age);}public static void print(int temp[]) {for (int i = 0; i < temp.length; i++) {System.out.print(temp[i] + "\t");}}}

程序运行结果:

112233445566778899--------------------------------------------------------------------123456789
















0 0
原创粉丝点击