java学习笔记23(Set接口)

Set接口:

  1.Set接口是不包含重复元素的Collection;

  2.set集合没有索引,只能通过增强型for循环或迭代器来遍历;

  3.Set接口只包含从collection接口继承的方法,并且增加了禁止重复元素这个限制。

  Set接口有HashSet类和LinkedHashSet类实现;

Set接口的实现类:HashSet类

   HashSet类特点:1.无序集合,

             2.可以存入空(null)

             3.不可以出现重复元素      示例:

import java.util.HashSet;

public class Demo2 {
    public static void main(String[] args) {
        HeshSetDemo();
    }

    private static void HeshSetDemo() {
        HashSet<String> h=new HashSet<>();
        h.add("张三");//继承Collection的add方法;
        h.add("李四");
        h.add("小明");
        h.add("王五");
        System.out.println(h);//[李四, 张三, 小明, 王五]  可以看出存储是无序的
        h.remove("张三");//继承Collection的remove方法
        System.out.println(h);//[李四, 小明, 王五]
        Object[] s = h.toArray();//将集合转数组方法toArray方法
        for (int i = 0; i <s.length ; i++) {
            System.out.println(s[i]);//李四    小明   王五
        }
        System.out.println();
        int size = h.size();//继承Collection的size方法
        System.out.println(size);//3
        boolean b = h.contains("小明");//继承Collection的contains方法
        System.out.println(b);//true
        h.clear();//继承Collection的clear方法
        System.out.println(h);//[]
        boolean empty = h.isEmpty();//继承Collection的isEmpty方法
        System.out.println(empty);//true

    }
}

2.Set接口实现类:LinkedHashSet类:

  LinkedHashSet类是HashSet的子类,它的方法与HashSet类一样,都是继承Collection接口的方法。

  LinkedHashSet是有序的   示例:

import java.util.Set;

public class Demo3 {
    public static void main(String[] args) {
        function();
    }

    private static void function() {
        String[] str={"aaa","bbb","ccc","ddd"};
        Set<String> s=new HashSet<>(Arrays.asList(str));
        System.out.println(s);//[aaa, ccc, bbb, ddd] Set无序集合
        HashSet<String> s1=new HashSet<>(Arrays.asList(str));
        System.out.println(s1);//[aaa, ccc, bbb, ddd] HashSet无序集合
        LinkedHashSet<String> s2=new LinkedHashSet<>(Arrays.asList(str));
        System.out.println(s2);//[aaa, bbb, ccc, ddd]  LinkedHashSet集合有序
    }
}

LinkedHashSet集合方法与HashSet方法一样,这里就不写了

原文地址:https://www.cnblogs.com/Zs-book1/p/10578363.html