论坛首页 入门技术论坛

多维迭代器

浏览 1801 次
锁定老帖子 主题:多维迭代器
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-01-08  
package com.test;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Hawkins
 * 
 * 
 *         多维集合迭代器
 */
public class MultiDimenIterator<T> {
	private Index[] table = new Index[255];// 数组从前到后,对应的是高位到低位。
	private int count = 0;
	private Map<Object, Collection<T>> dimens;

	public MultiDimenIterator(Map<Object, Collection<T>> dimens) {
		Set<Object> keySet = dimens.keySet();
		this.dimens = dimens;

		for (Object key : keySet) {
			this.addIndex(key, dimens.get(key).size());
		}
	}

	/**
	 * @param dimenID
	 * @param max
	 * @return
	 */
	private boolean addIndex(Object dimenID, int max) {
		if (isExist(dimenID)) {
			return false;
		}

		this.table[count] = new Index(dimenID, max);
		count++;
		return true;
	}

	/**
	 * @return
	 * 
	 *         返回当前游标指向的元素的所在位置,即各维度索引的数组
	 */
	@SuppressWarnings("unchecked")
	public Map<Object, T> getIndex() {
		Map<Object, T> result = null;

		boolean flag = move2Next();
		if (flag) {
			result = new HashMap<Object, T>();

			for (int i = 0; i < count; i++) {
				Object key = table[i].getDimenID();
				T value = (T) dimens.get(key).toArray()[table[i].getIndex()];
				result.put(key, value);
			}
		}

		return result;
	}

	/**
	 * @return
	 * 
	 *         游标指向下一个元素 进位加法,若最高位溢出,则返回false
	 */
	private boolean move2Next() {
		int i = count - 1;
		boolean nOverFlow = !table[i].addIndex();
		do {
			i--;

			if (nOverFlow == true && i >= 0) {
				nOverFlow = !table[i].addIndex();
			} else {
				break;
			}
		} while (i > 0);

		return nOverFlow;
	}

	private boolean isExist(Object dimenID) {
		for (int i = 0; i < count; i++) {
			if (table[i].getDimenID().equals(dimenID)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @author Hawkins
	 * 
	 *         标识某一维度的某元素的索引
	 */
	public static class Index {
		private Object dimenID;
		private int index = 0;// IMPORTANT
		private int length;

		public Index(Object dimenID, int length) {
			this.dimenID = dimenID;
			this.length = length;
		}

		public Object getDimenID() {
			return dimenID;
		}

		public void setDimenID(Object dimenID) {
			this.dimenID = dimenID;
		}

		public int getIndex() {
			return index;
		}

		/**
		 * @return if 溢出 return false else return true
		 */
		public boolean addIndex() {
			boolean flag;
			if (index + 1 == length) {
				flag = false;
			} else {
				flag = true;
			}
			index = (index + 1) % length;

			return flag;
		}

	}
}

代码假设每一个维度的集合,都有唯一的标识。并假设可以随机存取。
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics