集合框架(對(duì)象數(shù)組的概述和使用)

核心代碼:

package cn.ithelei;

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 + "]";
     }
}

ObjectArrayDemo

 package cn.ithelei;

/*
 * 我有5個(gè)學(xué)生,請(qǐng)把這個(gè)5個(gè)學(xué)生的信息存儲(chǔ)到數(shù)組中,并遍歷數(shù)組,獲取得到每一個(gè)學(xué)生信息。
 *       學(xué)生:Student
 *       成員變量:name,age
 *       構(gòu)造方法:無(wú)參,帶參
 *       成員方法:getXxx()/setXxx()
 *       存儲(chǔ)學(xué)生的數(shù)組?自己想想應(yīng)該是什么樣子的?
 * 分析:
 *      A:創(chuàng)建學(xué)生類(lèi)。
 *      B:創(chuàng)建學(xué)生數(shù)組(對(duì)象數(shù)組)。
 *      C:創(chuàng)建5個(gè)學(xué)生對(duì)象,并賦值。
 *      D:把C步驟的元素,放到數(shù)組中。
 *      E:遍歷學(xué)生數(shù)組。
 */
public class ObjectArrayDemo {
    public static void main(String[] args) {

    // 創(chuàng)建學(xué)生數(shù)組(對(duì)象數(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個(gè)學(xué)生對(duì)象,并賦值。
    Student s1 = new Student("林青霞", 27);
    Student s2 = new Student("梅超風(fēng)", 30);
    Student s3 = new Student("小哥", 18);
    Student s4 = new Student("趙雅芝", 60);
    Student s5 = new Student("王力宏", 35);

    // 把C步驟的元素,放到數(shù)組中。
    students[0] = s1;
    students[1] = s2;
    students[2] = s3;
    students[3] = s4;
    students[4] = s5;

    // 看到很相似,就想循環(huán)改
    // for (int x = 0; x < students.length; x++) {
    // students[x] = s + "" + (x + 1);
    // }
    // 這個(gè)是有問(wèn)題的

    // 遍歷
    for (int x = 0; x < students.length; x++) {
        // System.out.println(students[x]);

        Student s = students[x];
        System.out.println(s.getName() + "---" + s.getAge());
        }
    }

}
對(duì)象數(shù)組的內(nèi)存圖解

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容