首页 > 学院 > 开发设计 > 正文

数组(Array)

2019-11-14 23:54:28
字体:
来源:转载
供稿:网友
数组(Array)

1.数组(Array):相同类型数据的集合就叫做数组。

2. 数组的定义与赋值(系统会默认初始化)

普通数组:

 1 package com.li; 2  3 public class Array{ 4  5     public static void main(String[] args) { 6         // TODO 自动生成的方法存根 7         int[] a=new int[2];  8          9         /*10          * int a[]=new int[2];11          * int[] a={0,1};  12          * int[] a=new int[]{0,1};  //type[] 变量名 = {new type[]}{逗号分隔的初始化值列表};13          */14         a[0]=0;15         a[1]=1;16         System.out.PRintln(a[0]);17         System.out.println(a[1]);18         19         System.out.println("---------------------------------------");20         /*错误的方法21         int[] b = null;22         for(int i=0;i<10;i++){23             b[i]=i;24             System.out.println(b[i]);25         }26         */27         28         29     }

引用数组:

 1 public class Array{ 2  3     public static void main(String[] args) { 4         Person[] p=new Person[3]; 5         //数组内存放的是应用数据类型,指向对象,但初始为null 6         for(int i=0;i<p.length;i++){ 7             System.out.println(p[i]); 8         } 9         System.out.println("---------------------------------------");10         for(int i=0;i<p.length;i++){11             p[i]=new Person(i*10);12             System.out.println(p[i].age);13         }14     };15 }16 class Person{17     int age;18     public Person(int age){19         this.age=age;20     }21 }

3.java中的每个数组都有一个名为length的属性,表示数组的长度。length属性是public,final,int的。数组长度一旦确定,就不能改变大小。

4.二维数组。二维数组是一种平面的二维结构,本质上是数组的数组。二维数组的定义方式:type[][]a=new type[2][3];


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表