集合—HashSet

对于 HashSet 而言,它是基于 HashMap 实现的,底层采用 HashMap 来保存元素,所以如果对 HashMap 比较熟悉了。
HashSet和ArrayList区别:
HashSet无序不可重复,ArrayLIst有序可重复

HashSet(无序不重复)

1.add方法

//以下会去掉重复值
hashSet.add(100);
hashSet.add(100);
System.out.println(hashSet);
//只会输出一个100,并且没有get方法,因为无序不知道怎么获取

例:list去重

注:以下方法不可以,remove之后长度就变了,因为集合长度是变长的,所以这个方法不可行

//list集合去重
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("ddd");
arrayList.add("hhh");
arrayList.add("zs");
arrayList.add("zs");
arrayList.add("zl");
arrayList.add("zl");
for (int i = 0; i < arrayList.size(); i++) {
    String string = arrayList.get(i);
        if(arrayList.contains(string)) {
        arrayList.remove(string);
    }
}

用下面方法,直接list集合转化为set集合,因为set本身就是去重

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("ddd");
arrayList.add("hhh");
arrayList.add("zs");
arrayList.add("zs");
arrayList.add("zl");
arrayList.add("zl");
HashSet<String> hashSet = new HashSet<String>();
    for (String string : arrayList) {
            hashSet.add(string);
   }
System.out.println(hashSet);
//输出[zl, ddd, hhh, zs],会将重复值去掉

2.size方法输出元素个数大小

ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(11);
arrayList.add(22);
arrayList.add(33);
System.out.println("大小个数"+arrayList.size());
//输出3

3.isEmpty方法和contains方法

ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(11);
arrayList.add(22);
arrayList.add(33);
System.out.println("是否为空"+arrayList.isEmpty());
System.out.println("是否包含"+arrayList.contains(55));
//输出两个false 不为空和不包含55

posted @ 2022-10-16 13:18  花海~  阅读(38)  评论(0)    收藏  举报