更新時間:2021-05-06 13:30:18 來源:動力節點 瀏覽854次
在創建后,基本數據類型數組可以直接對數組元素賦值、引用等操作;而自定義對象數組,需要對數組中的每個對象元素獨立進行創建,然后才可以對其賦值、引用等操作,如果沒有單獨對每個對象添加元素,會導致空指針異常
1.基本數據類型數組
數組都要先聲明、再創建后使用。基本數據類型數組的聲明有以下幾種格式(以int類型為例):①int[]array;②int[]array=new int;③int[]array={1,2,3};int[]array=newint[]{1,2,3};以上幾種格式對數組內容操作,分為對數組的動態初始化和靜態初始化兩種形式。
2.自定義對象數組
自定義對象數組,它們由同一個類的多個具體實例有序組成。我們熟悉的主方法中的string args接收初始化參數時,參數就是一個典型的對象數組案例。由于其每個元素都是引用數據類型,數組在創建后,必須對每個對象分別進行實例化創建。
以自定義學生類student為例
public class Student
{
// 成員變量
private String name;
private int age;
// 構造方法
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)
{
// 創建學生數組(對象數組)。
Student[] students = new Student[5];
// for (int x = 0; x < students.length; x++)
// {
// System.out.println(students[x]);
// }
// System.out.println("---------------------");
// 創建5個學生對象,并賦值。
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);
// 將對象放到數組中。
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());
}
}
}
注意:對象數組在經過創建后只建立了棧內存的地址空間,因此在沒有對每個數組中的對象創建時輸出全部為null,只有經過每個對象實例的獨立地開辟堆內存空間,才能正確初始化數據對象。
以上就是動力節點小編介紹的"Java對象數組"的內容,希望對大家有幫助,如有疑問,請在線咨詢,有專業老師隨時為您服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習