标签:ima ati 笔记 index splay ide 效率 height imp
本文主要是参考《图解设计模式》写的读书笔记;
开发中我用到遍历集合时候,无非我常用的就是简单的for循环,foreach,iterator 这三种方式进行遍历!
当然这三种的效率:
学习Iterator模式时候,书上给的案例是这样的,一个书架上面放满了书,书下面有个指针!
大概就这样,画的不好!
首先这书架也就相当于是一个集合,集合中得book就是相当于集合元素,下面的指针就相当于Iterator中得hasNext();
为甚有那么简单的for循环不用,非要搞Iterator干嘛,我第一次时候就这么问的??
看案例吧:
1.先编写一个包含了迭代方法的抽象类
package iterator.Method; public interface Aggregate { public abstract Iterator iterator(); }
2.编写实体类
package iterator.Model; /** * * @author zengrong * */ public class Book { private String name; public Book(String name) { super(); this.name = name; } public String getName() { return name; } @Override public String toString() { return "Book [name=" + name + "]"; } }
package iterator.Model; import iterator.Method.Aggregate; import iterator.Method.Iterator; import iterator.Method.IteratorBookshelf; public class BookShelf implements Aggregate { private Book books[]; //定义指针的位置 private int last=0; //获取数据额书 public Book getBookAt(int index) { return books[index]; } public BookShelf(int maxsize) { this.books=new Book[maxsize]; } //获取长度 public int getLength() { return last; } //添加书 public void appendBook(Book book) { this.books[last]=book; last++; } //添加 @Override public Iterator iterator() { return new IteratorBookshelf(this); } }
3.编写抽象的iterator
package iterator.Method; /** * * @author zengrong * 对迭代接口设计二个方法 */ public interface Iterator { public abstract boolean has
Next(); public abstract Object next(); }
package iterator.Method; import iterator.Model.Book; import iterator.Model.BookShelf; /* * 遍历书架上面书的类 */ public class IteratorBookshelf implements Iterator{ private BookShelf bookShelf; private int index; public IteratorBookshelf(BookShelf bookShelf) { super(); this.bookShelf = bookShelf; } public boolean hasNext() { if(index<bookShelf.getLength()){ return true; }else{ return false;} } public Object next() { Book book = bookShelf.getBookAt(index); index++; return book ; } }
4 main
package Main; import iterator.Method.Iterator; import iterator.Model.Book; import iterator.Model.BookShelf; /** * * @author zengrong * 测试 */ public class App { public static void main(String[] args) { BookShelf bookShelf=new BookShelf(5); Book book =new Book("苍老师日语全集"); Book book2 =new Book("电影AV无码"); Book book3 =new Book("小泽从你的全世界路过"); Book book4 =new Book("自己动手丰衣足食"); Book book5 =new Book("给我一个杠杆我会撬动你"); bookShelf.appendBook(book); bookShelf.appendBook(book2); bookShelf.appendBook(book3); bookShelf.appendBook(book4); bookShelf.appendBook(book5); Iterator it = bookShelf.iterator(); while(it.hasNext()){ Book bo = (Book) it.next(); System.out.println(bo); } } }
标签:ima ati 笔记 index splay ide 效率 height imp
原文地址:http://www.cnblogs.com/java-synchronized/p/6637583.html