[新手求教]容器输出的问题
我想输出的是对象的属性
可是输出的是字符串。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StudentNew {
public static void main(String[] args) {
List list = new ArrayList();
Student a = new Student(1,"张三",18,"打球","语文",38);
Student b = new Student(2,"李四",18,"唱歌","数学",88);
Student c = new Student(3,"王五",18,"爬山","计算机",73);
Student d = new Student(4,"大侠",18,"打球","信息科学",76);
Student e = new Student(5,"九哥",18,"打球","软件工程",98);
list.add(a);
list.add(b);
list.add(c);
list.add(d);
list.add(e);
Object o = list.toArray();
Iterator i = list.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
public class Student {
int id;
String name;
int age;
String sal;
String project;
int grade;
public Student(){
}
public Student(int id, String name, int age, String sal, String project,
int grade) {
this.id = id;
this.name = name;
this.age = age;
this.sal = sal;
this.project = project;
this.grade = grade;
}
}
------解决方案--------------------public String toString(){
return "姓名"+this.name+"年龄"+this.age;
}
List<Student> s=new ArrayList<Student>();
s.add(new Son("张三",20));
s.add(new Son("李四",21));
s.add(new Son("王五",18));
System.out.println(s);
------解决方案--------------------Iterator i = list.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
你ArrayList里面存的就是对象,这样输出的就是一个对象在内存里的标识,如果要输出属性最好在Student类里面添加get和set方法.也可以像我这样
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StudentNew {
public static void main(String[] args) {
List list = new ArrayList();
Student a = new Student(1,"张三",18,"打球","语文",38);
Student b = new Student(2,"李四",18,"唱歌","数学",88);
Student c = new Student(3,"王五",18,"爬山","计算机",73);
Student d = new Student(4,"大侠",18,"打球","信息科学",76);
Student e = new Student(5,"九哥",18,"打球","软件工程",98);
list.add(a);
list.add(b);
list.add(c);
list.add(d);
list.add(e);
Object o = list.toArray();
Iterator i = list.iterator();
while(i.hasNext()){
System.out.println(((Student)i.next()).display());
}
}
}
public class Student {
int id;
String name;
int age;
String sal;
String project;
int grade;
public Student(){
}
public Student(int id, String name, int age, String sal, String project,
int grade) {
this.id = id;
this.name = name;
this.age = age;
this.sal = sal;
this.project = project;
this.grade = grade;
}
public String display()
{
return "ID:"+id+" 姓名:"+name+" age:"+age;
}
}