Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1740602
  • 博文数量: 438
  • 博客积分: 9799
  • 博客等级: 中将
  • 技术积分: 6092
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-25 17:25
文章分类

全部博文(438)

文章存档

2019年(1)

2013年(8)

2012年(429)

分类: Java

2012-03-25 22:04:30

这里仅概述Java中的容器。Java也是支持范型的,比如“ArrayList a = new ArrayList”。不带范型参数的容器默认为Object对象的集合。

容器包括两大类:CollectionMap,它们包括:
Collection:List(ArrayList、LinkedList)、Set(HashSet、TreeSet、LinkedHashSet)、Queue(PriorityQueue)。
Map:HashMap、TreeMap、LinkedHashMap。

Collection提供一个iterator()方法来返回一个迭代器(Iterator),一个Iterator要包含以下方法:hasNext()、next()和remove()(可选)。

为了支持Foreach的语法,一个类必须实现Iterable接口。这个接口有一个方法iterator()来得到一个迭代器。Collection实现了这个接口。下面的代码定义了支持Foreach的类:


  1. class MyCollection implements Iterable<Integer> {
  2.     public Iterator<Integer> iterator()
  3.     {
  4.         return new Iterator<Integer>() {
  5.             int i = 0;
  6.             public boolean hasNext() { return i < 10; }
  7.             public Integer next() { return i++;    }
  8.             public void remove() { throw new UnsupportedOperationException(); }
  9.         };
  10.     }
  11.     public static void main(String[] args)
  12.     {
  13.         MyCollection mc = new MyCollection();
  14.         for (int i: mc)
  15.             System.out.print(i);
  16.     }
  17. }


阅读(631) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~