`
小篮子java的家
  • 浏览: 30993 次
  • 性别: Icon_minigender_2
社区版块
存档分类
最新评论

TreeSet构造分析及简单实现

阅读更多
我们知道java集合大致上可分为:set,list,map三种体系,其中set代表无序不可重复的集合,list代表有序可重复的集合,map代表具有映射关系的集合。后来又增加一种Queue体系集合,代表一种队列的集合实现。每个体系根据内部实现原理的不同,实现了不同的类结构。
例如:常见的在list中就有ArrayList Map中有HashMap set中有HashSet,TreeSet...

今天对Treeset的一点小研究作以下分析:

第一:什么是TreeSet?
treeset在API中的解释是基于 TreeMap 的 NavigableSet 实现。使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator 进行排序,具体取决于使用的构造方法。
这里抛开这些听不懂的专业术语,用简易的语言来说一下。treeset就是按照一定的顺序,利用一种特殊的链表,将你要存储元素链起来的一种存储结构。后面会对这个“一定的顺序”和“特殊的链表”进行分析。

第二:为什么是"TreeSet"?
从这个名字分析TreeSet是由tree和set两部分组成。那么我们是不是可以理解这就是由tree形成的set。事实上,TreeSet的实现是依赖于TreeMap,而TreeMap 的实现就是红黑树数据结构,也就说是一棵自平衡的排序二叉树。

在这里插播一段关于TreeSet的实现是依赖于TreeMap的解释,这里的依赖其实就是说你实例化了的TreeSet对象,然后对其所做的操作,后台不过是将元素,和一个统一的value打包成一个映射再去拿到TreeMap里面执行相同的操作,返回值到TreeSet后,TreeSet再进行修饰修饰。当然你实例化TreeSet其实也是经过TreeMap实例化的。

接下来再聊排序二叉树。也就是上文提到的“特殊的链表”

二叉排序树(Binary Sort Tree)又称二叉查找树。 它或者是一棵空树;或者是具有下列性质的二叉树: (1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值; (2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值; (3)左、右子树也分别为二叉排序树;
接下来设想一下如果按照这个树的规则来插入,那我们插入一个结点之前必须要确定结点的位置。要确定这个结点的位置,势必也是与已经存在的树结构的某些结点进行比较。

所以到这里又要聊聊这个排序的问题,也就是上文提到的“一定的顺序”

这个一定的顺序到底是怎样的顺序呢,插入的元素可以是String,可以是int可以是各种类型,如果要比较他们的大小再根据排序二叉树的规则找到他们的位置插入或者进行其他操作。那这个大小究竟怎么去比较呢?再这里就不得不提API所说的“使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator 进行排序”这句话。这句话涉及到了两个跟排序有着密切关系的类分别是:comparable和Comparator。
照例,我们先看一下定义:
Comparable是一个对象本身就已经支持自比较所需要实现的接口,(String,Integer就可以自己进行比较大小的操作)
Comparator是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足你的要求时你可以写一个比较器来完成两个对象之间大小的比较。
这里的定义还是很好懂的。就是说:如果你要进行排序的对象如果选择了Comparable就让它直接继承这个接口然后重写Comparable的compareTo()方法,使用时这样两个对象就可以直接比较。而如果你选择了Comparator,你就需要重新写一个独立的类来继承Comparator这个接口然后重写它的compare(A a,B b)方法,在使用时用Comparator的对象调用compare(A a,B b)对两个对象进行比较。
这样看来comparable应该比较固定,和一个具体类相绑定,而comparator比较灵活,它可以被用于各个需要比较功能的类使用。可以说前者属于“静态绑定”,而后者可以“动态绑定”。

第三:怎样实现treeset
前面以将TreeSet的重点分析了一,二接下来就是细节和逻辑问题了,就直接上代码吧!
]

package mySet;

import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 实现一个简单的TreeSet
 * @author TJL
 */
public class MyTreeSet<E> implements Cloneable, java.io.Serializable {
	// 为set底层树的结构排序用的比较器 当按照E的自然排序时为null
	private final Comparator<? super E> comparator;
	// 头节点
	private transient SetNode<E> root = null;
	// 节点个数
	private transient int size = 0;

	/**
	 * 无参构造,设置比较器为null
	 */
	public MyTreeSet() {
		comparator = null;
	}

	/**
	 * 构造函数,传入定义好的比较器对象
	 * 
	 * @param comparator
	 *            :比较器对象
	 */
	public MyTreeSet(Comparator<? super E> comparator) {
		this.comparator = comparator;
	}

	/**
	 * 插入对象e到MyTreeSet中
	 * 
	 * @param e
	 *            :要插入的对象
	 * @return:返回是否插入成功
	 */
	public boolean add(E e) {
		SetNode<E> n = root;
		if (n == null) {
			root = new SetNode<E>(e, null);
			size = 1;
			return true;
		}
		int comp;
		SetNode<E> parents;
		Comparator<? super E> cptor = comparator;
		// 若比较器不为空 用Comparator进行比较
		if (cptor != null) {
			do {
				parents = n;
				comp = cptor.compare(e, n.e);
				if (comp < 0)
					n = n.left;
				else if (comp > 0)
					n = n.right;
				else {
					return false;
				}
			} while (n != null);
		} else {
			if (e == null)
				throw new NullPointerException();
			// 用定义好的自然顺序方法进行排序比较
			Comparable<? super E> cpb = (Comparable<? super E>) e;
			do {
				parents = n;
				comp = cpb.compareTo(n.e);
				if (comp < 0)
					n = n.left;
				else if (comp > 0)
					n = n.right;
				else {
					return false;
				}
			} while (n != null);
		}
		// 找到新元素将来位置的父结点后,将元素实例化成结点插入到树中
		SetNode<E> newNode = new SetNode<E>(e, parents);
		if (comp < 0)
			parents.left = newNode;
		else
			parents.right = newNode;
		size++;
		return true;
	}

	/**
	 * 返回是否含有元素e
	 * 
	 * @param e
	 * @return
	 */
	public boolean contains(E e) {
		return getNode(e) != null;
	}

	/**
	 * 删除元素e所在的结点
	 * 
	 * @param e
	 * @return
	 */
	public boolean remove(E e) {
		SetNode<E> node = getNode(e);// 找到元素e所在节点
		if (node == null)
			return false;
		deleteNode(node);// 进行删除
		return true;
	}

	/**
	 * 找到元素e在树中的结点
	 * 
	 * @param e
	 * @return
	 */
	private SetNode<E> getNode(E e) {
		SetNode<E> n = root;
		int comp;
		SetNode<E> parents;
		Comparator<? super E> cptor = comparator;
		// 若比较器不为空 用Comparator进行比较
		if (cptor != null) {
			do {
				parents = n;
				comp = cptor.compare(e, n.e);
				if (comp < 0)
					n = n.left;
				else if (comp > 0)
					n = n.right;
				else {
					return parents;
				}
			} while (n != null);
		} else {
			if (e == null)
				throw new NullPointerException();
			// 用定义好的自然顺序方法进行排序比较
			Comparable<? super E> cpb = (Comparable<? super E>) e;
			do {
				parents = n;
				comp = cpb.compareTo(n.e);
				if (comp < 0)
					n = n.left;
				else if (comp > 0)
					n = n.right;
				else {
					return parents;
				}
			} while (n != null);
		}
		return null;
	}

	/**
	 * 删除树中的节点node 当结点node有左右子女时,往下所搜与node中的元素最为接近的元素的结点
	 * 找到后将该结点的元素值赋给node,让node指向该结点, 接下来删除这个结点。 注意:最后要去掉的节点的子女个数都是小于2的
	 * 
	 * @param node
	 */
	void deleteNode(SetNode<E> node) {
		size--;
		SetNode<E> rep;
		if (node.left != null && node.right != null) {
			rep = replaceNode(node);
			node.e = rep.e;
			node = rep;
		}
		rep = (node.left != null ? node.left : node.right);

		if (rep != null) {
			rep.parents = node.parents;
			if (node.parents == null)
				root = rep;
			else if (node == node.parents.left)
				node.parents.left = rep;
			else if (node == node.parents.right)
				node.parents.right = rep;
		} else {
			if (node.parents == null) {
				root = null;
			}
			if (node.parents != null) {
				if (node == node.parents.left)
					node.parents.left = null;
				else if (node == node.parents.right)
					node.parents.right = null;
			}
		}
	}

	/**
	 * 找到距离node中的元素大小最近的结点
	 * 
	 * @param node
	 * @return
	 */
	SetNode<E> replaceNode(SetNode<E> node) {
		if (node == null)
			return null;
		else if (node.right != null) {
			SetNode<E> p = node.right;
			while (p.left != null)
				p = p.left;
			return p;
		} else {
			SetNode<E> p = node.parents;
			SetNode<E> ch = node;
			while (p != null && ch == p.right) {
				ch = p;
				p = p.parents;
			}
			return p;
		}
	}

	/**
	 * 清空set集合
	 */
	public void clear() {
		size = 0;
		root = null;
	}

	/**
	 * 返回结点的个数
	 * 
	 * @return
	 */
	public int size() {
		return size;
	}

	/**
	 * 找到最小的元素
	 * 
	 * @return
	 */
	public E first() {
		SetNode<E> p = root;
		if (p != null)
			while (p.left != null)
				p = p.left;
		if (p.e == null)
			throw new NoSuchElementException();
		else
			return p.e;
	}

	/**
	 * 找到最大的元素
	 * 
	 * @return
	 */
	public E last() {
		SetNode<E> p = root;
		if (p != null)
			while (p.right != null)
				p = p.right;
		if (p.e == null)
			throw new NoSuchElementException();
		else
			return p.e;
	}

	/**
	 * 找到最小的元素所在的结点
	 * 
	 * @return
	 */
	public SetNode<E> firstNode() {
		SetNode<E> p = root;
		if (p != null)
			while (p.left != null)
				p = p.left;
		if (p.e == null)
			throw new NoSuchElementException();
		else
			return p;
	}

	/**
	 * 迭代器
	 * @return
	 */
	public Iterator<E> iterator() {
		return new KeyIterator(firstNode(), this);
	}
}


package mySet;

import java.util.Iterator;
import java.util.NoSuchElementException;
/**
 * MyTreeset的迭代器
 * @author TJL
 * @param <E>
 */
public class KeyIterator<E> implements Iterator<E>{
	SetNode<E> next;
	SetNode<E> nowNode ;
	MyTreeSet<E> myTreeSet;
	public KeyIterator(SetNode<E> firstNode,MyTreeSet<E> set) {
		next = firstNode;
		nowNode=null;
		myTreeSet=set;
	}
	//是否含有下一个结点
	public boolean hasNext() {
		return next != null;
	}
	//返回下一个元素
	public E next() {
		return nextEntry().e;
	}
	//返回下一个元素结点
	private SetNode<E> nextEntry() {
		   nowNode = next;
         if (nowNode == null)
             throw new NoSuchElementException();
         next = myTreeSet.replaceNode(nowNode);
         return nowNode;
	}
	//删除下一个元素结点
	public void remove() {
		  if (nowNode == null)
                 throw new IllegalStateException();
		  if (nowNode.left != null && nowNode.right != null)
              next = nowNode;
		  myTreeSet.deleteNode(nowNode);
          nowNode = null;
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics