天天看点

java利用AbstractCollection实现自己的可迭代集合类

Colllection是  java.uitl包中所有集合类的一个根接口..  所以我们可以通过实现Collection接口来实现自己的集合类..

不过由于Collection接口 方法太多.. 于是JDK提供了AbstractCollection抽象类...

这个类是Collection的一个骨干..即为我们提供了Collection的大量实现..我们只需要实现  iterator 和size方法 ...如果我们想要修改自己创建的容器那么要实现add和remove方法否则 。。

进行修改操作会抛出UnSupporttedException异常   下面是一个例子 ...

在生成迭代器的时候结合局部内部类使用

package me;

import java.util.AbstractCollection;

import java.util.Iterator;

class Info{

 String info=null ;

 public Info(String name) {

     this.info=name ;

 }

 @Override

 public String toString() {

  return this.getClass().getName()+": "+info;

class  MyCollection extends  AbstractCollection<Info>{ 

 private Info []arr =new Info[100];

 private int count= 0; 

 public  boolean add(Info info){

  if(count<=arr.length){

      arr[count++]=info ;

   return true ;

  }

  return false; 

 public boolean equals(Object obj) {

  // TODO Auto-generated method stub

  return super.equals(obj);

 public Iterator<Info> iterator() {

  return new Iterator<Info>() {

   private int flag=0 ;

   @Override

   public boolean hasNext() {

    return flag<MyCollection.this.count ;

   }

   public Info next() {

    return arr[flag++];

   public void remove() {   //支持删除操作

          throw new  UnsupportedOperationException() ;     

  };

 public int size() {

  return 0;

public class Me   {  

 public static void main(String []agrs){ 

  MyCollection me=new MyCollection() ;

  me.add(new Info("zhangsan ")) ;

  me.add(new Info("lisi ")) ;

  me.add(new Info("zwangwu ")) ;

  me.add(new Info("zmaliu ")) ;

  for(Info i:me){

   System.out.println(i);

}