zoukankan      html  css  js  c++  java
  • java中Set的用法

    Set集合的特点:

    不能存储相同的元素。

    同时因为其是一个抽象的接口:所以不能直接实例化一个set对象。(Set s = new Set() )错误

    该接口主要继承于Collections接口,所以具有Collection的一些常见的方法。

    常见的方法:

    方法 解释
    add( ) 向集合中添加元素
    clear( ) 去掉集合中所有的元素
    contains( ) 判断集合中是否包含某一个元素
    isEmpty( ) 判断集合是否为空
    iterator( ) 主要用于递归集合,返回一个Iterator()对象
    remove( ) 从集合中去掉特定的对象
    size( ) 返回集合的大小

    Set接口最长用的两大实现:HashSet TreeSet

    TreeSet:会将里面的元素默认排序。

    Set<Integer> test = new TreeSet<>();
    int a = 1;
    int b = 8;
    int c = 3;
     
    test.add(a);
    test.add(b);
    test.add(c);
     
     //遍历集合test   利用foreach遍历          //输出结果:1   3   8    
     for (Integer value : test) {
         System.out.print(value+" ");
     }    
    
    //利用Iterator实现遍历
    Iterator<Integer> value = test.iterator();
    while (value.hasNext()) {
        int s = value.next();
        System.out.print(s+" ");
    }                                //输出结果:1   3   8
    
  • 相关阅读:
    [紫书] 八数码问题(BFS)
    [紫书] 移动盒子(Boxes in a Line)
    [洛谷] P1803 凌乱的yyy / 线段覆盖 (贪心)
    [紫书] 破损的键盘(Broken Keyboard)
    bzoj3891
    poj3233
    bzoj1941
    Vijos2034
    poj2985
    Vijos1100
  • 原文地址:https://www.cnblogs.com/eternityz/p/java_set.html
Copyright © 2011-2022 走看看