如何使用迭代器?遍历Set集合?看这里
package com.set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.class1.NewTitle;
public class SetDemo {
public static void main(String[] args) {
NewTitle title1 = new NewTitle (1,"北京终于晴天了1","admin");
NewTitle title2 = new NewTitle (2,"北京终于晴天了2","admin");
NewTitle title3 = new NewTitle (3,"北京终于晴天了3","admin");
NewTitle title4 = new NewTitle (4,"北京终于晴天了4","admin");
NewTitle title5 = new NewTitle (5,"北京终于晴天了5","admin");
Set set = new HashSet();
set.add(title1);
set.add(title2);
set.add(title3);
set.add(title4);
set.add(title5);
System.out.println("新闻总记录数: "+set.size());
/**
*
*
* 遍历无序的集合 (1)增强型 (2)iterator迭代器
* 遍历有序的集合(1)普通for,遍历索引 (2)增强型for (3)Iterator迭代器
* */
System.out.println("-----------------使用for增强型----------------------");
//遍历每条新闻信息
for ( Object obj:set) {
NewTitle title =(NewTitle) obj;
System.out.println(title.getId()+"-"+title.getTitle());
}
System.out.println("-----------------使用迭代器遍历无序----------------------");
//使用迭代器遍历
Iterator itor =set.iterator(); //获得迭代器 itor
//通过迭代器的迭代集合
while( itor.hasNext()) { //判断下一个元素有没有,如果有往下移
NewTitle title = (NewTitle) itor.next();
System.out.println(title.getId()+"-"+title.getTitle());
}
}
}