FAQ2.24 数组如何定义和初始化?

答:

    本文讲述了Java数组的几个相关的方面,讲述了对Java数组的声明、创建和初始化,并给出其对应的代码。

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

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

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

    实例:
    TestNew.java:

    程序代码:

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

初始化:

1.动态初始化:数组定义与为数组分配空间和赋值的操作分开进行;
2.静态初始化:在定义数字的同时就为数组元素分配空间并赋值;
3.默认初始化:数组是引用类型,它的元素相当于类的成员变量,因此数组分配空间后,每个元素也被按照成员变量的规则被隐士初始化。
实例:

TestD.java(动态):

程序代码:

  1. public class TestD 
  2.      public static void main(String args[]) { 
  3.          int a[] ; 
  4.          a = new int[3] ; 
  5.          a[0] = 0 ; 
  6.          a[1] = 1 ; 
  7.          a[2] = 2 ; 
  8.          Date days[] ; 
  9.          days = new Date[3] ; 
  10.          days[0] = new Date(2008,4,5) ; 
  11.          days[1] = new Date(2008,2,31) ; 
  12.          days[2] = new Date(2008,4,4) ; 
  13.      } 
  14.  
  15. class Date 
  16.      int year,month,day ; 
  17.      Date(int year ,int month ,int day) { 
  18.          this.year = year ; 
  19.          this.month = month ; 
  20.          this.day = day ; 
  21.      } 
  22.  

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.  
  9. class Time    
  10. {    
  11.      int hour,min,sec ;    
  12.      Time(int hour ,int min ,int sec) {    
  13.          this.hour = hour ;    
  14.          this.min = min ;    
  15.          this.sec = sec ;    
  16.      }    
  17. }   

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. }

相关文章:

  • 2021-12-10
  • 2022-12-23
  • 2021-11-28
  • 2021-05-28
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案