利用JAVA陣列模擬集合實現簡單的物件陣列的新增
阿新 • • 發佈:2019-01-23
public class Student
{
Student[] stu;
int count;
String name;
int age;
public Student(){
stu=new Student[5];
}
public Student(String name,int age){
this.name=name;
this.age=age;
}
public void addStu(String name,int age){
stu[count]=new Student(name,age);
count++;
}
public Student getStu(int index){
return stu[index];
}
public int getCount(){
return count;
}
public static void main(String[] agrs){
Student student=new Student();
student.addStu("張三",21);
student.addStu("李四",20);
student.addStu("王五",27);
for(int i=0;i<student.getCount();i++){
System.out.println("第"+(i+1)+"個學生:姓名:"+student.getStu(i).name+" 年齡:"+student.getStu(i).age);
}
}
}
{
Student[] stu;
int count;
String name;
int age;
public Student(){
stu=new Student[5];
}
public Student(String name,int age){
this.name=name;
this.age=age;
}
public void addStu(String name,int age){
stu[count]=new Student(name,age);
count++;
}
public Student getStu(int index){
return stu[index];
}
public int getCount(){
return count;
}
public static void main(String[] agrs){
Student student=new Student();
student.addStu("張三",21);
student.addStu("李四",20);
student.addStu("王五",27);
for(int i=0;i<student.getCount();i++){
System.out.println("第"+(i+1)+"個學生:姓名:"+student.getStu(i).name+" 年齡:"+student.getStu(i).age);
}
}
}