Set集合常用方法

  • set集合接口也属于Collection的常用接口,其最大特点是不允许出现重复数据
  • TreeSet中是有序的容器,所以如果将散乱的set集合中的元素放入到TreeSet中,那么会自动排好序。(前提是放入的元素的类实现了Comparable接口
  • hashset只能增删不能改查,set就像一个集合一样,没有角标,所以不能定位元素(像茶壶煮饺子到倒不出来),而且hashset是根据散列hash存储元素的,所以看起来是无序的。

1、增

  • add();
  • addAll(Collection);
public static void main(String[] args) {
        List<String> list = new LinkedList<>();
        list.add("hello");
        list.add(0, "world");
        list.add("MLDN");
        list.add("www.mldn.cn");
        Set<String> set = new HashSet<>();
        set.add("A");
        set.add("B");
        set.add("C");
        set.add("D");
        set.add("F");
        set.addAll(list);
        System.out.println(set);
}

这里可以了解一下TreeSet,TreeSet是一个有序集合,即使在插入的时候没有顺序,那么在输出的时候就是都会是有序的了。但是使用TreeSet的时候,插入的对象要是实现了Comparable接口才可以正常使用。

2、删

  • remove(T t); 根据元素内容删除元素
    public static void main(String[] args) {

        Set<String> set = new HashSet<>();
        set.add("A");
        set.add("B");
        set.add("C");
        set.add("D");
        set.add("F");
        System.out.println(set);

        System.out.println(set.remove("A"));
        
    }

3、遍历

1、for-each遍历

 public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("A");
        set.add("B");
        set.add("C");
        set.add("D");
        set.add("F");

        for (String s : set) {
            System.out.println(s);
        }
    }

2、迭代器遍历

public static void main(String[] args) {

        Set<String> set = new HashSet<>();
        set.add("A");
        set.add("B");
        set.add("C");
        set.add("D");
        set.add("F");

        Iterator<String> i = set.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());
        }
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值