java.数组

什么是数组

数组是一组数据类型相同的数据的组合,将这些数据统一的管理起来
数组是一个引用数据类型,数组内存的类型可以是基本类型,也可以是引用类型
数组的定义(声明)
数据类型[] 数组名字:
    int[] x;
    char[] y;
    boolean[] z;
    String[] m;
其他的定义方式:
    int x[];
    int []x;
数组的赋值(初始化)
静态初始化  有长度 有元素
    int[] array = new int[]{10,23,30,40,50};
    int[] array = {10,20,30,40,50};
动态初始化  有长度 没有元素(不是真的没有 是保存默认值)
    int[] array = new int[5];
    整数默认值--0
    浮点数默认值--0.0
    字符类型默认值--char对应0的字解码  比如 97对应a 65对应A 48对应‘0’
    布尔型默认值--false
    引用数据默认值--null
    
访问元素
通过元素在数组的位置index(索引/下标)来访问
索引是有取值范围的【从0开始-数组长度-1】
如果数组的索引超出了上述范围
会出现一个运行异常 ArrayIndexOutOfBoundsException (数组索引超出边界)
数组元素的遍历(轮询)
通过循环的方式访问数组的每一个元素
JDK1.5版本之后 新的特性 增强for循环: forEach
for(自定义的变量(用于接收数组内的每一个元素): 遍历的数组Array){
}

正常的for 
    有三个必要条件 index索引 找到某一个位置
    可以通过index直接访问数组的某一个位置 存值 取值都可以
增强的for
    有两个必要条件 用来取值的变量 用来的遍历的数组 没有index索引
    不能存值 只能取值
    没有index索引 找不到元素到底是哪一个
声明 初始化 访问 遍历
 
public class TestArray {
    public static void main(String[] args) {
        
        //初始化一个数组
        int[] array = new int[] {10,20,30,40,50};
        
        //从数组内去的某一个元素
        int value = array[2];
        System.out.println(value);//30
        System.out.println(array[3]);//30
        
        //向数组内存入一个元素
        array[4] = 500;
        System.out.println(array[4]);//500
        
        //正常for遍历数组
        for(int index=0;index<5;index++) {
            System.out.println(array[index]);
        }
        /* 10
         * 20
         * 30
         * 40
         * 500
         */
        
        System.out.println("---------------------------------");
        //增强for遍历数组
        for(int v:array) {
            System.out.println(v);
        }
        /* 10
         * 20
         * 30
         * 40
         * 500
         */
        }
}
  

猜你喜欢

转载自www.cnblogs.com/youngleesin/p/11572525.html
今日推荐