集合 01 集合基础 & 基于二分搜索树的集合

集合接口 - Set(ADT)

  • 集合中的元素不能重复;
public interface Set {

    void add(E e);
    boolean contains(E e);
    void remove(E e);
    int getSize();
    boolean isEmpty();
    
}

基于 BST 的 Set 实现

  • 之前实现的 BST 也不能存储重复元素,当然 BST 是可以设计成可存储重复元素的;
  • BSTSet 中的泛型是要求具有可比较性的,因为 BST 中的泛型是要求具有可比较性的;
public class BSTSet> implements Set {

    private BST bst;

    public BSTSet(){
        bst = new BST<>();
    }

    @Override
    public int getSize(){
        return bst.size();
    }

    @Override
    public boolean isEmpty(){
        return bst.isEmpty();
    }

    @Override
    public void add(E e){
        bst.add(e);
    }

    @Override
    public boolean contains(E e){
        return bst.contains(e);
    }

    @Override
    public void remove(E e){
        bst.remove(e);
    }
    
}

测试代码 - 词频统计

public class Main {

    public static void main(String[] args) {
        System.out.println("Pride and Prejudice");

        ArrayList words1 = new ArrayList<>();
        if(FileOperation.readFile("pride-and-prejudice.txt", words1)) {
            System.out.println("Total words: " + words1.size());

            BSTSet set1 = new BSTSet<>();
            for (String word : words1)
                set1.add(word);
            System.out.println("Total different words: " + set1.getSize());
        }
        

        System.out.println();


        System.out.println("A Tale of Two Cities");

        ArrayList words2 = new ArrayList<>();
        if(FileOperation.readFile("a-tale-of-two-cities.txt", words2)){
            System.out.println("Total words: " + words2.size());

            BSTSet set2 = new BSTSet<>();
            for(String word: words2)
                set2.add(word);
            System.out.println("Total different words: " + set2.getSize());
        }
    }
    
}
输出
Pride and Prejudice
Total words: 125901
Total different words: 6530

A Tale of Two Cities
Total words: 141489
Total different words: 9944

你可能感兴趣的:(集合 01 集合基础 & 基于二分搜索树的集合)