我是靠谱客的博主 无语红牛,这篇文章主要介绍【Java---集合存储学生对象并遍历】,现在分享给大家,希望可以做个参考。

学生类:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package student.error.student; public class Student { private String name; private int age; //有参跟无参构造方法 public Student(){ } public Student(String name,int age){ this.name=name; this.age=age; } //成员变量对应的get跟set方法 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; } }

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package student.error.student; //需求:创建一个存储学生对象的集合,存储3个学生对象,使用程序是现在控制台遍历该集合 import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class CollectionDemo { public static void main(String[] args) { //创建Collection集合对象 Collection<Student> c=new ArrayList<Student>(); //创建学生对象 Student s1=new Student("小明",20); Student s2=new Student("小红",21); Student s3=new Student("小华",22); //把学生添加到集合 c.add(s1); c.add(s2); c.add(s3); //遍历集合(迭代器方式) Iterator<Student> it=c.iterator(); while (it.hasNext()){ Student s=it.next(); System.out.println(s.getName()+","+s.getAge()); } } }

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package student.error.student; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListDemo { public static void main(String[] args) { //创建List集合列表 List<Student> list=new ArrayList<Student>(); //创建学生对象 Student s1=new Student("小明",30); Student s2=new Student("小红",31); Student s3=new Student("小化",32); //把学生添加到集合 list.add(s1); list.add(s2); list.add(s3); //通过迭代器方式 Iterator<Student> it=list.iterator(); while(it.hasNext()){ Student s=it.next(); System.out.println(s.getName()+','+s.getAge()); } System.out.println("------------------------------"); //通过for循环方式 for(int i=0;i<list.size();i++){ Student s=list.get(i); System.out.println(s.getName()+','+s.getAge()); } } }

最后

以上就是无语红牛最近收集整理的关于【Java---集合存储学生对象并遍历】的全部内容,更多相关【Java---集合存储学生对象并遍历】内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(132)

评论列表共有 0 条评论

立即
投稿
返回
顶部