首页 > 其他分享 >集合—HashSet

集合—HashSet

时间:2022-10-16 13:22:06浏览次数:42  
标签:zl hashSet arrayList HashSet add 集合 zs

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("djm");
arrayList.add("hzj");
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("djm");
arrayList.add("hzj");
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, djm, hzj, zs],会将重复值去掉

标签:zl,hashSet,arrayList,HashSet,add,集合,zs
From: https://www.cnblogs.com/YHSDDJM/p/16796059.html

相关文章