Java 一维数组作为参数和返回值

一维数组作为参数:

  • 传数组的引用
  • 创建数组直接传,本质也是传数组的引用
  • 传null
public class Test {
    
    //数组作为参数时,可以传递3中形式
    public void m1(int[] a) {
        System.out.println("数组长度是:"+ a.length);
    }
    
    public static void main(String[] args) {
        Test t = new Test();
        
        //创建一个数组,传递数组引用
        int[] b = {1,2,3,4,5};
        t.m1(b);
        //直接创建数组传值
        t.m1(new int[]{1,2,3});
        //直接传递null,但是次数组不可用
        t.m1(null);    
    }
}

 

一维数组作为返回值:

  • 返回数组的引用
  • 直接创建一个数组返回,本质上是返回数组的引用
  • 返回null
public class Test {
    
    //返回数组的引用
    public String[] m1() {
        String[] s = {"abc","de"};
        return s;
    }
    
    //返回直接创建的数组
    public String[] m2() {
        return new String[]{"a", "b","c"};
    }
    
    //返回null
    public String[] m3() {
        return null;
    }
    
    public static void main(String[] args) {
        Test t = new Test();
        
        String[] s1 = t.m1();
        System.out.println("接收到的数组长度:" + s1.length);
        String[] s2 = t.m2();
        System.out.println("接收到的数组长度:" + s2.length);
        String[] s3 = t.m3();
        System.out.println("接收到的数组长度:" + s3.length);
    }
}
posted @ 2017-11-13 11:07  LeeAaron  阅读(9271)  评论(0编辑  收藏  举报