注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 DOS命令杀掉进程
 帮助

容器:我的java笔记(3)


2008-03-31 11:41:30
 标签:java基础   [推送到技术圈]

Iterator接口以及set接口解说。

各种类库中:
Iterator接口:
所有实现了Collection接口的容器类都有一个iterator方法,用以返回一个实现了Iterator接口的对象。
Iterator对象称作为迭代器,方便实现对容器内元素的遍历操作。
Iterator接口定义:
Boolean hasNext();
Object next();
Void remove();
 
import java.util.*;
public class Test_Iterator
{
public static void main(String[] args)
{
Collection c = new HashSet();
c.add(new Name2("f1","l1"));
c.add(new Name2("f2","l2"));
c.add(new Name2("f3","l3"));
Iterator i=c.iterator();
while(i.hasNext())
{
Name2 n=(Name2)i.next();
System.out.print(n.getFirstName()+" ");
}
}
}
 
 
注意:
含有一个例子:
 
Collection c new HashSet();
c.add(new Name2("f1","l1"));
c.add(new Name2("f2","l2"));
c.add(new Name2("f3","l3"));
for(Iterator i=c.iterator(); i.hasNext();)
{
Name name=(Name)i.next();
if(name.getFirstName().length()<3)
{
i.remove();//注意 这里不能换成c.removename); 会产生例外,
//也就是说当iterator接口调用对象时,其他接口对象不能对该对象进行操作,叫锁定
}
使用API文档熟悉Set方法:
public static void main(string arg[])
{
Set s1= new hashset();
set s2 = new hashset();
s1.add(“a”);
s2.add(“a”);s2.add(“b”);
Set sn= new HashSet(s1);
sn.retainAll(s2);
Set su=new HashSet(s1);
su.addall(s2);
}




    文章评论
 
 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: