您的位置:首页 > 其它

集合框架(对象数组的概述和使用)

2016-04-27 19:36 232 查看
package cn.itcast_01;
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 + "]";
}
}
最上层放成员变量,接着是构造方法(构造方法和成员变量之间一般我会空一行),各个成员方法我都有空行(构造方法写完之后,我一般会写getXXX()和setXXX()方法) alt+shift+s+回(在Myeclipse里面面快速写出toString()方法)
package cn.itcast_01;
/*
* 我有5个学生,请把这个5个学生的信息存储到数组中,并遍历数组,获取得到每一个学生信息。
*   学生:Student
*   成员变量:name,age
*   构造方法:无参,带参
*   成员方法:getXxx()/setXxx()
*   存储学生的数组?自己想想应该是什么样子的?
* 分析:
*   A:创建学生类。
*   B:创建学生数组(对象数组)。
*   C:创建5个学生对象,并赋值。
*   D:把C步骤的元素,放到数组中。
*   E:遍历学生数组。
*/
public class ObjectArrayDemo {
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("赵雅芝", 60);
Student s5 = new Student("王力宏", 35);
// 把C步骤的元素,放到数组中。
students[0] = s1;
students[1] = s2;
students[2] = s3;
students[3] = s4;
students[4] = s5;
// 看到很相似,就想循环改
// for (int x = 0; x < students.length; x++) {
// students[x] = s + "" + (x + 1);
// }
// 这个是有问题的
// 遍历
for (int x = 0; x < students.length; x++) {
//System.out.println(students[x]);

Student s = students[x];
System.out.println(s.getName()+"---"+s.getAge());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息