Java遍曆數組對象的方式__Java·

來源:互聯網
上載者:User

本人總結有三:估計還有很多,只是感覺這幾個比較常用而已。。歡迎大家在文章下面討論:


代碼不做解釋

要明白編寫的代碼在電腦中是怎麼儲存的。以本代碼為例:首先你要知道你執行執行個體  例如stu[0]=new Student("張三", 18);,這樣是在堆空間裡面建立一個Student空間裡面存放各種屬性,而stu[0]儲存的是指向這個空間的一個地址。所以遍曆出來就是這個地址;又如Student stu = new Student("name",age);這個stu是個引用,你把stu列印出來就是列印這個地址,假如你列印能列印屬性,那一個對象的屬性有很多,那系統要列印哪個屬性呢。  (執行個體一、執行個體二)


執行個體一:

public class Student {private String name;private int age;public Student(String name, int age) {this.name=name;this.age=age;}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;}public void show(){System.out.println(name+"\t"+age);}public static void main(String[] args) {Student [] stu =new Student[5];stu[0]=new Student("張三", 18);stu[1]=new Student("趙四", 19);stu[2]=new Student("王五", 20);stu[3]=new Student("老六", 21);stu[4]=new Student("老七", 22);for(int i=0; i<stu.length; i++){stu[i].show();}}}

執行個體二:


public class Student {private String name;private int age;public Student(String name, int age) {this.name=name;this.age=age;}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;}public static void main(String[] args) {Student [] stu =new Student[5];stu[0]=new Student("張三", 18);stu[1]=new Student("趙四", 19);stu[2]=new Student("王五", 20);stu[3]=new Student("老六", 21);stu[4]=new Student("老七", 22);
for(int i=0; i<stu.length; i++){System.out.println(stu[i].getName()+"\t"+stu[i].getAge());}}}

執行個體三: 用到重寫toString()     是在類裡面的最下面重寫  to在MyEclipse的KeyTip,能快速打出


public class Student {private String name;private int age;public Student(String name, int age) {this.name=name;this.age=age;}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;}public static void main(String[] args) {Student [] stu =new Student[5];stu[0]=new Student("張三", 18);stu[1]=new Student("趙四", 19);stu[2]=new Student("王五", 20);stu[3]=new Student("老六", 21);stu[4]=new Student("老七", 22);for(int i=0; i<stu.length; i++){<span style="white-space:pre"></span>System.out.println(stu[i]);}}@Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + "]";}}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.