数据结构学习(六):集合(Set)

版权声明:文章为作者原创,若要转载请获得作者同意。尊重版权,从你我做起! https://blog.csdn.net/qq_37768971/article/details/88425215

一、本节学习目标:

集合:集合是JAVA常用的数据结构,集合中不允许有重复的元素存在,在许多场合有着广泛的应用,如:

查找一本小说中的英文单词数(不重复);

实现集合的基本功能:

1.boolean isEmpty();
2.boolean contains(E e);
3.void add(E e);
4.void remove(E e);
5.int getSize();

二、具体代码和注解:

1.Set接口

public interface Set<E> {
     boolean isEmpty();
     boolean contains(E e);
     void add(E e);
     void remove(E e);
     int getSize();
}

2.基于之前LinkedList实现的LinkedListSet

LinkedList实现的页面:https://blog.csdn.net/qq_37768971/article/details/88201883

代码

package IMUHERO;
import java.util.ArrayList;
public class LinkedListSet<E> implements Set<E> {
   LinkedList<E>linkedList;
   LinkedListSet(){
       linkedList=new LinkedList<>();
   }

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

    @Override
    public void add(E e) {
        if (linkedList.contains(e))return;
        else linkedList.addFirst(e);
    }

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

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

3.基于基于之前BST实现的BSTSet

LinkedList实现的页面:https://blog.csdn.net/qq_37768971/article/details/88376363

代码:

package IMUHERO;

public class BSTSet<E extends Comparable<E>> implements Set<E> {
    private BST<E> bst;
    //构造方法
    public BSTSet(){
        bst=new BST<>();
    }
    @Override
    public boolean isEmpty(){
        return bst.isEmpty();
    }
    @Override
    public boolean contains(E e){
        return bst.contains(e);
    }
    @Override
    public void add(E e){
        bst.add(e);
    }
    @Override
    public int getSize(){
        return bst.size();
    }
    @Override
    public void remove(E e){
        bst.remove(e);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_37768971/article/details/88425215