一、基本数据类型数组
数组都要先声明、再创建后使用。基本数据类型数组的声明有以下几种格式(以int类型为例):
①int[]array;
②int[]array=new int;
③int[]array={1,2,3};int[]array=newint[]{1,2,3};
以上几种格式对数组内容操作,分为对数组的动态初始化和静态初始化两种形式。在程序中对数组的动态赋值操作,如下代码所示:
public class test{
public static void main(string args[]){
int[] arrayi;
arrayi=new int[3];
/*int[]arrayi=new int[3];*/ //或用以上格式声明及创建数组
*for(int i=0;i system.out.println(”\n动态初始化后:”);
arrayi[0]=1;arrayi[1]=2;arrayi[2]=3;for(inti=0;i
上述程序运行结果:0、0、0;动态初始化后:1、2、3。
从以上程序结果分析,在整型数组中,单个数组元素就像整型变量一样,被创建后值存储于内存中,可以直接向数组元素赋值,直接对其引用操作。
二、自定义对象数组
自定义对象数组,它们由同一个类的多个具体实例有序组成。我们熟悉的主方法中的string args接收初始化参数时,参数就是一个典型的对象数组案例。由于其每个元素都是引用数据类型,数组在创建后,必须对每个对象分别进行实例化创建。以自定义学生类student为例,学生类定义如下:
class student{
private string name;
public student(string name){this.name=name;}
public string getname(){return this.name;}}
自定义对象的数组声明及初始化格式有以下几种:①student[]array;array=new student[3];②student[]array=new student[3];③student[]array=newstudent[]{new student(”lilei”),newstudent(”cili”),new student(”wuxi”)};student[]array={newstudent(”lilei”),new student(”cili”),new student(”wuxi”)};
对自定义对象数组动态初始化操作,代码如下:
class student{
private string name;
public student(string name){this.name=name;}
public string getname(){return this.name;}}
public class test {
public static void main(string args[]){
student array[];
array=new student[3];
/*student[]array=newstudent[3];*/
for(int i=0;i array[0]=new student(”lilei”);
array[1]=new student(”cili”);
array[2]=new student(”wuxi”);
system.out.println(”动态初始化后:”);
for(int i=0;i
上述程序的运行结果:null、null、null;动态初始化后:lilei、cili、wuxi。从对象数组动态初始化程序运行结果分析,对象数组在经过创建后只建立了栈内存的地址空间,因此在没有对每个数组中的对象创建时输出全部为null,只有经过每个对象实例的独立地开辟堆内存空间,才能正确初始化对象数据。
三、总结
java中基本数据类型数组与自定义对象数组的区别是,在创建后,基本数据类型数组可以直接对数组元素赋值、引用等操作;而自定义对象数组,需要对数组中的每个对象元素独立进行创建,然后才可以对其赋值、引用等操作,如果没有单独对每个对象元素创建,会导致空指针异常。