数组

数组是最简单一种数据结构

  //数组的声明与创建:变量类型 变量名=变量的值
        double []array_01;//推荐
        int array[];//c与c++类型的

 

package com.xuyifan.function;

/**
 * @author xyf
 * @create 2020-08-13-15:23
 */
public class Demo07 {
    public static void main(String[] args) {
        //数组的声明与创建:变量类型 变量名=变量的值
        double []array_01;//推荐
        int array[];//c与c++类型的
        //数组类型 []数组名=new 类型[数组的空间]
        //数组类型 []数组名=new 类型[]{穷举所有数组成员}
        double []numbers1=new double[6];//动态初始化,包含默认初始化
        int []numbers2=new int[]{1,2,3,4,5,6};//静态初始化
        for (int i = 0; i < numbers1.length ; i++) {
            System.out.print(numbers1[i]+"\t");
        }
        System.out.println();
        for (int i = 0; i < numbers2.length; i++) {
            System.out.print(numbers2[i]+"\t");

        }
    }
}

输出

0.0    0.0    0.0    0.0    0.0    0.0    
1    2    3    4    5    6    

 

数组小结:

  • 数组的长度是固定的,在创建时,数组的长度就固定了
  • 数组里的元素必须是相同的数据类型
  • 数组里的元素可以是任何类型,既可以是基本类型,也可以是引用类型
  • 数组变量属于引用类型,数组也可以看成对象,数组中的每个元素相当于成员变量,数组本身就是对象,java的所有对象是在堆中

下标的合法区间 [0,length-1],超过就会出现下标越界异常抛出 

java.lang.ArrayIndexOutOfBoundsException
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
    at com.xuyifan.function.Demo07.main(Demo07.java:24)

 小练习:数组反转:

package com.xuyifan.function;

/**
 * @author xyf
 * @create 2020-08-13-16:58
 */
public class Demo08 {
    public static void main(String[] args) {
        int []array1=new int []{1,2,3,4,5,6};
        int []array2=reverse(array1);
        for (int i = 0; i < array2.length; i++) {
            System.out.print(array2[i]+"\t");
        }

    }
    public static int[] reverse(int[]arrays){
        int []result=new int[arrays.length];
        for (int i = 0,j= arrays.length-1; i < arrays.length ; i++,j--) {
            result[i]= arrays[j];
        }
        return result;
    }
}

输出:

6    5    4    3    2    1    

 

posted @ 2020-08-13 16:48  jueqishizhe  阅读(41)  评论(0)    收藏  举报