比较Iterator和ListIterator

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

/**
 * compare iterator efficiency.
 * @author sailing
 * Date: 2007-10-01
 */
public final class CompareIterator {
 /**
  * define instance as single.
  */
     private static CompareIterator instance = new CompareIterator();
 /**
  * construct CompareIterator class.
  */
 private CompareIterator() {
 }
    /**
     * get single.
     * @return instance
     */
 public static CompareIterator getInstance() {
  return instance;
 }
 /**
  * init data.
  * @return list
  */
 private List initData() {
  List list = new ArrayList();
  Map map = null;
  int size = 10000;
  for(int i = 0; i < size; i++) {
   map = new HashMap();
   map.put("key"+i, "value"+2*i);
   list.add(map);
  }
  return list;
 }
 /**
  * get system current time.
  * @return time
  */
 private Long getCurrentTime(){
  Long time = 0l;
  time = System.currentTimeMillis();
  return time;
 }
 /**
  * read by iterator.
  * @param list
  */
 private void readByIterator(List list) {
  Iterator it = (Iterator) list.iterator();
  Map map = null;
  while(it.hasNext()){
   map = (HashMap) it.next();
  }
  System.out.println("ReadByIterator End.");
 }
 /**
  * read by list iterator.
  * @param list list
  */
    private void readByListIterator(List list) {
  ListIterator li = list.listIterator();
  Map map = null;
  while(li.hasNext()){
   map = (HashMap) li.next();
  }
  System.out.println("ReadByListIterator End.");
 }
    /**
     * main.
     * @param args
     */
    public static void main(String []args) {
  CompareIterator ci = new CompareIterator();
  List list = ci.initData();
  long startTime1 = 0;
  long startTime2 = 0;
  long endTime1 = 0;
  long endTime2 = 0;
  
  startTime1 = ci.getCurrentTime();
  ci.readByIterator(list);
  endTime1 = ci.getCurrentTime();
  
  startTime2 = ci.getCurrentTime();
  ci.readByListIterator(list);
  endTime2 = ci.getCurrentTime();
  
  System.out.println("ReadByIterator Need Time: " + (endTime1 - startTime1));
  System.out.println("ReadByListIterator Need Time: " + (endTime2 - startTime2));
  
 }
}

你可能感兴趣的:(java)