存储不重复元素的容器,有链表LinkedSet有序,由二分搜索树实现ThreeSet有序 自然排序,由哈希表实现HashSet无序。
集合set接口定义
package shujujiegou_interface;
public interface Set<E> extends Iterable<E>{
public void add(E element);
public void remove(E element);
public boolean contains(E element);
public int size();
public boolean isEmpty();
}
由链表实现
package 树形结构;
import shixianClass02.LinkedList;
import shujujiegou_interface.Set;
import java.util.Iterator;
//底层由链表实现的集合 有序
public class LinkedSet<E> implements Set<E> {
private LinkedList<E> list;
public LinkedSet(){
list=new LinkedList<>();
}
//向集合中添加一个元素element 如果元素已存在则不添加
@Override
public void add(E element) { //O(n)
if(!list.contains(element)){
list.add(element);//O(n)
}
}
@Override
public void remove(E element) {
list.remove(element);
}
@Override
public boolean contains(E element) {
return list.contains(element);
}
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public Iterator<E> iterator() {
return list.iterator();
}
@Override
public String toString() {
return list.toString();
}
}
由二分搜索树实现set
package 树形结构;
import shujujiegou_interface.Set;
import 查找算法.BinarySearch;
import java.util.Iterator;
//底层由二分搜索树实现的集合 有序 自然排序
public class TreeSet<E extends Comparable<E>> implements Set<E> {
private BinarySearchTree<E> tree;
public TreeSet(){
tree=new BinarySearchTree<>();
}
@Override
public void add(E element) { //O(logn)
tree.add(element);
}
@Override
public void remove(E element) {
tree.remove(element);
}
@Override
public boolean contains(E element) {
return tree.contains(element);
}
@Override
public int size() {
return tree.size();
}
@Override
public boolean isEmpty() {
return tree.isEmpty();
}
@Override
public Iterator<E> iterator() {
return tree.iterator();
}
@Override
public String toString() {
return tree.toString();
}
}
测试链表实现和二分搜索树实现的set效率:
package ceshi;
import shujujiegou_interface.Set;
import 树形结构.FileOperation;
import 树形结构.LinkedSet;
import 树形结构.TreeSet;
import java.util.ArrayList;
public class TestSet {
static ArrayList<String> words;
public static void main(String[] args) {
words=new ArrayList<>();
FileOperation.readFile("pride-and-prejudice.txt",words);
TreeSet<String> ts=new TreeSet<>();
System.out.println("TerrSet:");
countingWords(ts);
System.out.println(ts.size());
System.out.println("------------------------------");
LinkedSet<String> ls=new LinkedSet<>();
System.out.println("LinkedSet:");
countingWords(ls);
System.out.println(ls.size());
}
private static void countingWords(Set<String> set) {
long startTime=System.currentTimeMillis();
for(String word:words){
set.add(word);
}
long endTime=System.currentTimeMillis();
System.out.println("时间:"+(endTime-startTime)+"ms");
}
}
执行结果
TerrSet:
时间:30ms
6530
------------------------------
LinkedSet:
时间:509ms
6530
可以看出由二分搜索树效率比较高。