java小程序之从方法中返回数组

java使用值传递pass by value的方法将实参传递给方法。传递基本数据类型变量的值与传递数组值会有很大的不同。
1. 传递基本数据类型的参数,传递的是实参的值。
2. 对于数组类型参数,参数值是数组的引用,给方法传递的是这个引用,参数共享pass-by-sharing。
从方法中返回数组的代码1:

//将数组逆序输出,传入数组,并从方法中返回数组
//没有改变原来的数组顺序
public class Demo032601{
    public static int[] reverse( int[] list ){
        int[] result = new int[ list.length ];
        for (int i = 0, j = list.length-1 ; i < list.length; i++, j-- ){
            result[ j ] = list[ i ];
        }
        return result;
    }
    public static void main( String [] args ){
        int[] list1 = { 2, 4, 5, 7, 9,16 };
        System.out.print( "list1原数组\n" );
        for ( int i = 0; i < list1.length; i++ ){
            System.out.print( list1[i] + "\t" );
        }
        System.out.print( "\n" );
        int[] list2 = reverse( list1 );
        System.out.print( "list2逆序数组\n" );
        for ( int i = 0; i < list2.length; i++ ){
            System.out.print( list2[i] + "\t" );
        }
        System.out.print( "\n" );
        System.out.print( "list1原数组\n" );
        for ( int i = 0; i < list1.length; i++ ){
            System.out.print( list1[i] + "\t" );
        }
        System.out.print( "\n" );
    }
}

从方法中返回数组的代码2:

//将数组逆序输出,传入数组,并从方法中返回数组
//改变了原来的数组顺序
public class Demo032602{
    public static int[] reverse( int[] list ){
        int[] result = new int[ list.length ];
        for (int i = 0, j = list.length-1 ; i < list.length; i++, j-- ){
            result[ j ] = list[ i ];
        }
        for ( int i = 0; i < list.length; i++){
            list[i] = result[i];
        }
        return list;
    }
    public static void main( String [] args ){
        int[] list1 = { 2, 4, 5, 7, 9,16 };
        System.out.print( "list1原数组\n" );
        for ( int i = 0; i < list1.length; i++ ){
            System.out.print( list1[i] + "\t" );
        }
        System.out.print( "\n" );
        int[] list2 = reverse( list1 );
        System.out.print( "list2逆序数组\n" );
        for ( int i = 0; i < list2.length; i++ ){
            System.out.print( list2[i] + "\t" );
        }
        System.out.print( "\n" );
        System.out.print( "list1原数组\n" );
        for ( int i = 0; i < list1.length; i++ ){
            System.out.print( list1[i] + "\t" );
        }
        System.out.print( "\n" );
    }
}

关于值传递的代码:

//比较传递基本数据类型变量和传递数组值
public class Demo032603{
    public static void test( int a, int[] b ){
        a = 1000;
        b[0] = 1111;
        System.out.println( "test.a = " + a );
        System.out.println( "test.b[0] = " + b[0] );
    }
    public static void main( String [] args ){
        int x = 1;
        int [] y = { 2 };
        System.out.println( "x = " + x );
        System.out.println( "y[0] = " + y[0] );
        test( x, y );
        System.out.println( "x = " + x );
        System.out.println( "y[0] = " + y[0] );
    }
}

你可能感兴趣的:(java)