常用JAVA API :HashSet 和 TreeSet

set容器的特点是不包含重复元素,也就是说自动去重。

HashSet

HashSet基于哈希表实现,无序。

add(E e)//如果容器中不包含此元素,则添加。
clear()//清空
contains(Object o)//查询指定元素是否存在,存在返回true
isEmpty()// 判空
iterator()//返回此容器的迭代器
remove// 如果指定元素在此set中则移除
size()//返回元素数量

TreeSet

基于红黑树实现。有序。

add(E e)// 如果不存在,则添加。
clear()//清空
contains(Object o)//查询指定元素是否存在,存在返回true
isEmpty()// 判空
iterator()//返回此容器的迭代器
remove// 如果指定元素在此set中则移除
size()//返回元素数量

以上方法都和HashSet一致,由于是红黑树实现的,所以TreeSet和TreeMap可以二分查找一个比当前元素大的最小元素,或者比当前元素小的最大元素。

ceiling(E e)//返回一个大于等于当前元素的最小元素,不存在返回null
floor(E e)//返回一个小于等于当前元素的最大元素,不存在返回null

higher(E e)//返回此 set 中严格大于给定元素的最小元素,不存在返回null
lower(E e)//返回此set中严格小于给定元素的最大元素,不存在返回null

first()//返回第一个元素
last()//返回最后一个元素

声明:

TreeSet<Integer> s = new TreeSet<>(); 
HashSet<Integer> s = new HashSet<>(); 

实例:

public class SetDemo {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
        TreeSet<Integer> s= new TreeSet<>();
        s.add(10);
        s.add(20);
        s.add(30);
        for (int x : s) {
            out.write(x + "\n");
        }
        /* 建议增强for
        Iterator<Integer> it = s.iterator();
         while (it.hasNext()){
            int x = it.next();
            out.write(x+"\n");
        }
         */
        out.write("\n");
        out.write(s.lower(20)+"\n");
        out.flush();
    }
}

输出:
10
20
30

10

猜你喜欢

转载自www.cnblogs.com/wangzheming35/p/12336073.html