数组

2017-08-07  本文已影响0人  xiaoliman

接触过java数组 但是没有系统总结过 今天学习之前 定义数组的格式老是忘
1.首先是声明格式(三种):
int[] a = new int[10];
int a[] = new int[]{1,2,3} ;
int[] a={1,2,3};
2.具体见有道<数组>笔记
3.另外 ,值得一记的是foreach语句

// i 代表的是数组的数值变量名  而不是下标   a是数组名字
  for(int i:a){
  system.out.println(i);
} 

4.使用foreach语句,还要注意空指针异常的情况

  for(String string:strings){
//要注意string为null的情况  会发生空指针异常
     System.out.peintln(string.length() );
}

看代码

package com.qf.demo2;

public class Test5 {

    public static void main(String[] args) {
        char[] cs = new char[6];
        cs[0] = 'a';
        
        double d[] = new double[9];
        d[0] = 7.8;
        
        
        String[] strings = new String[3];
        strings[0] = "a";
        strings[1] = new String("b");
        strings[2] = null;// 有可能会造成空指针
        // "a"  "b"  null
        for (String string : strings) {
            System.out.println(string.length());
            //System.out.println(string);
        }
        
    }
}

5.之前未接触过的可变长度参数: 参数有几个都行.底层用数组实现的 可用foreach输出

test(String... args){
for(String string:args)
   System.out.println(string);
}
//普通的输出语句
for(int i=0;i<args.length  i++){
    System.out.println(args[i]);
}

6.可变长度参数只能出现在形式参数列表的最后一个位置
test(String a,String b,String... c){ }
看例子:

package com.qf.demo3;
/**
 * 可变长度参数: 能出现在形式参数列表上
 */
public class Test {

    public static void main(String[] args) {
        test("米饭","馒头","饼","面条");
        play("小明", "水","土","泥巴");
    }
    // 可变长度参数
    // 底层利用的是数组
    public static void test(String... args){// 操作  可变长度参数的   当做是数组操作
        //System.out.println(args);
        for (String string : args) {
            System.out.println(string);
        }
        
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
    //  可变长度参数 只能出现在 形式参数列表的最后一个位置
    public static void play(String name,String... type){
        System.out.println(name);
        for (int i = 0; i < type.length; i++) {
            System.out.println(type[i]);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读