更新時間:2021-05-06 13:30:18 來源:動力節(jié)點 瀏覽845次
在創(chuàng)建后,基本數(shù)據(jù)類型數(shù)組可以直接對數(shù)組元素賦值、引用等操作;而自定義對象數(shù)組,需要對數(shù)組中的每個對象元素獨立進(jìn)行創(chuàng)建,然后才可以對其賦值、引用等操作,如果沒有單獨對每個對象添加元素,會導(dǎo)致空指針異常
1.基本數(shù)據(jù)類型數(shù)組
數(shù)組都要先聲明、再創(chuàng)建后使用。基本數(shù)據(jù)類型數(shù)組的聲明有以下幾種格式(以int類型為例):①int[]array;②int[]array=new int;③int[]array={1,2,3};int[]array=newint[]{1,2,3};以上幾種格式對數(shù)組內(nèi)容操作,分為對數(shù)組的動態(tài)初始化和靜態(tài)初始化兩種形式。
2.自定義對象數(shù)組
自定義對象數(shù)組,它們由同一個類的多個具體實例有序組成。我們熟悉的主方法中的string args接收初始化參數(shù)時,參數(shù)就是一個典型的對象數(shù)組案例。由于其每個元素都是引用數(shù)據(jù)類型,數(shù)組在創(chuàng)建后,必須對每個對象分別進(jìn)行實例化創(chuàng)建。
以自定義學(xué)生類student為例
public class Student
{
// 成員變量
private String name;
private int age;
// 構(gòu)造方法
public Student()
{
super();
}
public Student(String name, int age)
{
super();
this.name = name;
this.age = age;
}
// 成員方法
// getXxx()/setXxx()
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public String toString()
{
return "Student [name=" + name + ", age=" + age + "]";
}
}
public class Practice
{
public static void main(String[] args)
{
// 創(chuàng)建學(xué)生數(shù)組(對象數(shù)組)。
Student[] students = new Student[5];
// for (int x = 0; x < students.length; x++)
// {
// System.out.println(students[x]);
// }
// System.out.println("---------------------");
// 創(chuàng)建5個學(xué)生對象,并賦值。
Student s1 = new Student("小一", 27);
Student s2 = new Student("小二", 30);
Student s3 = new Student("小四", 30);
Student s4 = new Student("小五", 12);
Student s5 = new Student("小六", 35);
// 將對象放到數(shù)組中。
students[0] = s1;
students[1] = s2;
students[2] = s3;
students[3] = s4;
students[4] = s5;
// 遍歷
for (int x = 0; x < students.length; x++)
{
//System.out.println(students[x]);
Student s = students[x];
System.out.println(s.getName()+"---"+s.getAge());
}
}
}
注意:對象數(shù)組在經(jīng)過創(chuàng)建后只建立了棧內(nèi)存的地址空間,因此在沒有對每個數(shù)組中的對象創(chuàng)建時輸出全部為null,只有經(jīng)過每個對象實例的獨立地開辟堆內(nèi)存空間,才能正確初始化數(shù)據(jù)對象。
以上就是動力節(jié)點小編介紹的"Java對象數(shù)組"的內(nèi)容,希望對大家有幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為您服務(wù)。
初級 202925
初級 203221
初級 202629
初級 203743