基于平衡二叉树实现Set
public class AVLTreeSet<E extends Comparable<E>> implements ISet<E> { private AVLTree<E,Object> avl; public AVLTreeSet(){ avl = new AVLTree<E, Object>(); } public void add(E e) { avl.add(e,null); } public void remove(E e) { avl.remove(e); } public boolean contains(E e) { return avl.contains(e); } public int getSize() { return avl.getSize(); } public boolean isEmpty() { return avl.isEmpty(); } }
多种Set对比
public static void main(String[] args) { BinarySearchTreeSet<String> set2 = new BinarySearchTreeSet<String>(); double time2 = testSet(set2); System.out.println("二分搜索树Set花费" + time2); AVLTreeSet<String> avlSet = new AVLTreeSet<String>(); double time3 = testSet(avlSet); System.out.println("平衡二叉树Set花费" + time3); LinkedListSet<String> set1 = new LinkedListSet<String>(); double time1 = testSet(set1); System.out.println("链表Set花费" + time1); }
testSet方法
private static double testSet(ISet<String> set){ long startTime = System.nanoTime(); String[] arr = {"张三", "李四","王五", "赵六","张三丰","李思明","王老五","赵明"}; for(int i = 0; i < 30000; i++){ for(String str : arr){ set.add(str +i); } } long endTme = System.nanoTime(); return (endTme - startTime) / 1000000000.0; }
输出结果:
二分搜索树Set花费0.165575024
平衡二叉树Set花费0.127797361
链表Set花费花费249.458582022