JAVA问题 急!!!

来源:百度知道 编辑:UC知道 时间:2019/09/15 21:41:33
请问怎么从ArrayList 中输出一个对象的数据

先是一个JAVABEAN

//Student.java

public class Student{
private String stuName;
private String stuSex;
private String stuTEL;
Student(){
}
Student(String stuName,String stuSex,String stuTEL){
setStuName(stuName);
}
public void setStuName(String stuName){
this.stuName = stuName;
setStuSex(stuSex);
setStuTEL(stuTEL);
}
public void setStuSex(String stuSex){
this.stuSex = stuSex;
}
public void setStuTEL(String stuTEL){
this.stuTEL = stuTEL;
}
public String getStuName(){
return this.stuName;
}
public String getStuSex(){
return this.stuSex;
}
public String getStuTEL(){
return this.stuTEL;
}

}

下面是JSP代码中片断

先把如下信息放到二个 Student 对象里面。

姓名 性别 电话
Jackson 男 110
lucy 女 123

Student student = new Student("Jackson","男","110");
Student student1 = new Student("lucy","女","110");

List list = new ArrayList();
list.add(student);
list.add(student1);
...............................

要求在JSP页面输出如下格式信息。

姓名 性别 电话
Jackson 男 110
lucy 女 123

我试了输出,忘记了,一时想不起来。急,请教各位了。谢谢,多谢!

out.print("姓名 性别 电话<br>");
for(int i=0;i<list.getLength();i++)
{
out.print(((Student)list[i]).getStuName());
out.print(" "+((Student)list[i]).getStuSex());
out.print(" "+((Student)list[i]).getStuTEL());
out.print("<br>");
}

-----------------
还有
Student student = new Student("Jackson","男","110");
Student student1 = new Student("lucy","女","110");

List list = new ArrayList();
list.add(student);
list.add(student1);

这步可以这样写:
List list = new ArrayList();
list.add(new Student("Jackson","男","110"));
list.add(new Student("lucy","女","110"));

楼上错了,List没有这么用的list[i],要用遍历器
Iterator it = list.iterator();
Student stu;
while(it.hasNext())
{
stu = (Student)it.next();
out.print(stu.getStuName());
.......
}

这个首先你要打印Student对象你要覆盖toString方法
public String toString(){
return this.stuName+" "+this.stuSex+" "+this.stuTEL;
}

然后用个for-each循环,或者是Iterator来依次输出ArrayList中的元素!

for-each

for (Object o:h1){
System.out.println(o);
}

Iterator

Iterator it=h1.iterator();
while(it.hasNext()){
System.out.println(it.next());
}