详解一维数组

05-19 17:24992浏览

一维数组是由数字组成的以单纯的排序结构排列的结构单一的数组。一维数组是计算机程序中最基本的数组。二维及多维数组可以看作是一维数组的多次叠加产生的。一维数组算是Java数组中毕竟基本的部分,下面我们全面来学习一维数组。

1.声明方式

方式一

数据类型 数组名[] = null ;   //声明一维数组
数组名 = new 数组类型[长度]; // 分配内存给数组
复制代码

方式二

数据类型[] 数组名 = null ;   //声明一维数组
数组名 = new 数组类型[长度]; // 分配内存给数组
复制代码

简写方式

数据类型 数组名[] = new 数据类型[个数]; //声明数组的同时分配内存
复制代码

2.数组中元素的表示方法

1)数组的声明以及简单输出

package com.shxt.demo01;

public class ArrayDemo01 {
    public static void main(String[] args) {
        int[] score = null; //声明数组,但是为开辟内存空间
        score = new int[3]; //为数组开辟"堆内存"空间

        System.out.println("score[0]="+score[0]); //分别输出数组的每个元素
        System.out.println("score[1]="+score[1]); //分别输出数组的每个元素
        System.out.println("score[2]="+score[2]); //分别输出数组的每个元素

        // 使用循环依次输出数组中的全部内容
        for (int i = 0; i < 3; i++) {
            System.out.println("score["+i+"]="+score[i]);
        }
    }
}

对于数组的访问采用"数组名称[索引或者下标]"的方式,索引从0开始计数,假设程序中取出的内容超过了这个下标范围,例如:score[3]程序运行会存在以下的异常错误提示信息:

java.lang.ArrayIndexOutOfBoundsException:3

提示的内容为数组索引超出绑定的异常(经常说的数组越界异常),这个是未来你们初学者经常出现的问题,请引起重视.此外,我们发现以上的程序运行的结果的内容都是"0",这是因为声明的数组是整型数组.

2)为数组中的元素赋值并进行输出

声明整型数组,长度为5,通过for循环赋值1,3,5,7,9的数据

package com.shxt.demo01;

public class ArrayDemo02 {
    public static void main(String[] args) {
        int[] score = null; //声明数组,但是为开辟内存空间
        score = new int[5]; //为数组开辟"堆内存"空间

        for (int i = 0; i < 5; i++) {
            score[i] = i*2+1;
        }

        for (int i = 0; i < 5; i++) {
            System.out.println("score["+i+"]="+score[i]);
        }

    }
}

3)数组长度的取得

数组名称.length  --> 返回一个int型的数据
package com.shxt.demo01;

public class ArrayDemo03 {
    public static void main(String[] args) {
        int[] score =  new int[5];
        System.out.println("数组长度为:"+score.length);
    }
}

3. 数组的初始化方式

之前练习的就是使用的动态初始化方式

package com.shxt.demo01;

public class ArrayDemo04 {
    public static void main(String[] args) {
        int[] score = null; //声明数组,但是为开辟内存空间
        score = new int[3]; //为数组开辟"堆内存"空间
		
      	score[0] = 100;
        score[1] = 200;
        score[2] = 300;
    }
}
数据类型[] 数组名={初始值0,初始值1,...,初始值N}
或者
数据类型[] 数组名 = new 数据类型[]{初始值0,初始值1,...,初始值N}
package com.shxt.demo01;

public class ArrayDemo04 {
    public static void main(String[] args) {
        int[] score =  {10,20,30,40,50};
        for (int i = 0; i < score.length; i++) {
            System.out.println("score["+i+"]="+score[i]);
        }
    }
}

本文的一维数组就讲到这里,想要学习更多的Java数组的知识可以到动力节点在线观看免费的视频课程。

0人推荐
共同学习,写下你的评论

2 {{item.nickname}}

{{item.create_time}}

  {{item.zan}}