A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

一维数组的声明方式:
type var[]; 或type[] var;

声明数组时不能指定其长度(数组中元素的个数),

Java中使用关键字new创建数组对象,格式为:
数组名 = new 数组元素的类型 [数组元素的个数]

实例:
TestNew.java:

程序代码:
  1. public class TestNew  
  2. {  
  3.      public static void main(String args[]) {  
  4.          int[] s ;  
  5.          int i ;  
  6.          s = new int[5] ;  
  7.          for(i = 0 ; i < 5 ; i++) {  
  8.              s[i] = i ;  
  9.          }  
  10.          for(i = 4 ; i >= 0 ; i--) {  
  11.              System.out.println("" + s[i]) ;  
  12.          }  
  13.      }   
  14. }
复制代码


初始化:
1.动态初始化:数组定义与为数组分配空间和赋值的操作分开进行;
2.静态初始化:在定义数字的同时就为数组元素分配空间并赋值;
3.默认初始化:数组是引用类型,它的元素相当于类的成员变量,因此数组分配空间后,每个元素也被按照成员变量的规则被隐士初始化。
实例:
TestD.java(动态):
程序代码:
  1. public class TestD  
  2. {  
  3.      public static void main(String args[]) {  
  4.          int a[] ;  
  5.          a = new int[3] ;  
  6.          a[0] = 0 ;  
  7.          a[1] = 1 ;  
  8.          a[2] = 2 ;  
  9.          Date days[] ;  
  10.          days = new Date[3] ;  
  11.          days[0] = new Date(2008,4,5) ;  
  12.          days[1] = new Date(2008,2,31) ;  
  13.          days[2] = new Date(2008,4,4) ;  
  14.      }  
  15. }  

  16. class Date  
  17. {  
  18.      int year,month,day ;  
  19.      Date(int year ,int month ,int day) {  
  20.          this.year = year ;  
  21.          this.month = month ;  
  22.          this.day = day ;  
  23.      }  
  24. }  
复制代码

TestS.java(静态):
程序代码:
  1. public class TestS     
  2. {     
  3.      public static void main(String args[]) {     
  4.          int a[] = {0,1,2} ;     
  5.          Time times [] = {new Time(19,42,42),new Time(1,23,54),new Time(5,3,2)} ;     
  6.      }     
  7. }     

  8. class Time     
  9. {     
  10.      int hour,min,sec ;     
  11.      Time(int hour ,int min ,int sec) {     
  12.          this.hour = hour ;     
  13.          this.min = min ;     
  14.          this.sec = sec ;     
  15.      }     
  16. }   
复制代码

TestDefault.java(默认):

程序代码:
  1. public class TestDefault     
  2. {     
  3.      public static void main(String args[]) {     
  4.          int a [] = new int [5] ;     
  5.          System.out.println("" + a[3]) ;     
  6.      }     
  7. }   
复制代码

1 个回复

倒序浏览
type[] arr = new arr{}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马