Java学习3

来源:互联网 发布:php在线讲解 编辑:程序博客网 时间:2024/04/30 19:52

1.foreach可以用来循环遍历数组和实现Iterable接口元素。这里Set, List,Queue都继承Collection接口,而Colleciton接口继承自Iterable:

public interface Collection<E> extends Iterable<E>

特别的是foreach可以用于对基本数据类型数组和String数组的遍历,虽然它们没有实现Iterable接口。并且foreach只具有遍历作用,不能修改值。

2.Collection有三个子接口分别是Set,List,Queue

    Iterator,迭代器类,实现了三个方法next(),hasnext(),remove() 

    Iterable,一种接口,仅包含一个方法Iterator<E> iterator()

从网上摘要的:

为什么一定要实现Iterable接口,为什么不直接实现Iterator接口呢? 

因为Iterator接口的核心方法next()或者hasNext() 是依赖于迭代器的当前迭代位置的。如果Collection直接实现Iterator接口,势必导致集合对象中包含当前迭代位置的数据(指针)。当集合在不同方法间被传递时,由于当前迭代位置不可预置,那么next()方法的结果会变成不可预知。除非再为Iterator接口添加一个reset()方法,用来重置当前迭代位置。但即时这样,Collection也只能同时存在一个当前迭代位置。而Iterable则不然,每次调用都会返回一个从头开始计数的迭代器。多个迭代器是互不干扰的。

3.Set类型的遍历只能使用foreach或者iterator

4.HashMap的3种遍历方法  这里面讲解的很详细HashMap的机制,http://blog.csdn.net/vozon/article/details/5458370

  4.1for(Map.Entry<KeyType,ValueType> entry: hashmap.entrySet())  //entrySet获取键值对

       System.out.printIn(entry.getKey()+entry.getValue())

  4.2Iterator it=hashmap.keySet().iterator();//keySet获取值的集合

     while(it.hasNext())

        System.out.printIn(it.next());   

  4.3Iterator it=hashmap.entrySet().iterator();

      while(it.hasNext())

         {

             Entry entry=(Entry)it.next();

             System.out.printIn(entry.getKey().toString()+entry.getValue().toString());

         }

0 0