JAVA集合-集合的遍历
发布日期:2021-09-29 01:27:00 浏览次数:8 分类:技术文章

本文共 1810 字,大约阅读时间需要 6 分钟。

JAVA集合-集合的遍历

前面我们讲了最简单的集合遍历用for循环。

今天再介绍两个 Iterator和foreach;

首先是Iterator遍历器,我们给下实例:

先给一个Student类:

package com.java1234.chap08.sec03; public class Student {     private String name;    private Integer age;                   public Student() {        super();        // TODO Auto-generated constructor stub    }    public Student(String name, Integer age) {        super();        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer 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
package 
com.java1234.chap08.sec03;
 
import 
java.util.Iterator;
import 
java.util.LinkedList;
 
 
public 
class 
TestIterator {
 
    
public 
static 
void 
main(String[] args) {
        
LinkedList<Student> list=
new 
LinkedList<Student>();
        
list.add(
new 
Student(
"张三"
,
10
));
        
list.add(
new 
Student(
"李四"
,
20
));
        
list.add(
new 
Student(
"王五"
,
30
));
         
        
/**
         
* 用Iterator遍历集合
         
*/
        
Iterator<Student> it=list.iterator();  
// 返回一个迭代器
        
while
(it.hasNext()){
            
Student s=it.next();   
// 返回迭代的下一个元素。
            
System.out.println(
"姓名:"
+s.getName()+
"年龄:"
+s.getAge());
        
}
    
}
}

姓名:张三年龄:10

姓名:李四年龄:20

姓名:王五年龄:30

foreach遍历:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package 
com.java1234.chap08.sec03;
 
import 
java.util.LinkedList;
 
 
public 
class 
TestForeach {
 
    
public 
static 
void 
main(String[] args) {
        
LinkedList<Student> list=
new 
LinkedList<Student>();
        
list.add(
new 
Student(
"张三"
,
10
));
        
list.add(
new 
Student(
"李四"
,
20
));
        
list.add(
new 
Student(
"王五"
,
30
));
         
        
/**
         
* 用foreach遍历
         
*/
        
for
(Student s:list){
            
System.out.println(
"姓名:"
+s.getName()+
"年龄:"
+s.getAge());
        
}
    
}
}

运行输出:

姓名:张三年龄:10

姓名:李四年龄:20

姓名:王五年龄:30

关键字:                  

转载地址:https://blog.csdn.net/happydecai/article/details/80249358 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LinkedList的pop()和push()方法
下一篇:JAVA集合-Set集合

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月15日 04时02分19秒