集合 02 基于链表的集合

本文介绍了一种基于链表实现的集合类LinkedListSet,用于处理不重复元素的集合操作,通过词频分析测试其性能。对比BSTSet,虽然在速度上略显逊色,但在元素去重方面表现良好。

基于链表的集合

  • 由于Set中的元素要求不能重复,故在添加元素时做了去重判断,这点相对于BSTSet要特别注意一下;
public class LinkedListSet<E> implements Set<E> {

    private LinkedList<E> list;

    public LinkedListSet(){
        list = new LinkedList<>();
    }

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

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

    @Override
    public void add(E e){
        if(!list.contains(e))
            list.addFirst(e);
    }

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

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

}

测试代码 - 词频分析

public static void main(String[] args) {

    System.out.println("Pride and Prejudice");

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

        LinkedListSet<String> set1 = new LinkedListSet<>();
        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<String> words2 = new ArrayList<>();
    if(FileOperation.readFile("a-tale-of-two-cities.txt", words2)){
        System.out.println("Total words: " + words2.size());

        LinkedListSet<String> set2 = new LinkedListSet<>();
        for(String word: words2)
            set2.add(word);
        System.out.println("Total different words: " + set2.getSize());
    }
}

输出:

  • 结果上和BSTSet是一样的,但明显可以感觉出速度上慢很多;
  • 对于BSTSet和LinkedListSet的时间复杂度的分析,参见下一篇文章
Pride and Prejudice
Total words: 125901
Total different words: 6530

A Tale of Two Cities
Total words: 141489
Total different words: 9944
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值