不限空间的免费网站,wordpress分类页置顶信息,长沙设计公司排行,中工互联网站建设#xff08;1#xff09;Set集合
Set也是集合中的一个容器#xff0c;程序可以依次把若干个对象放进Set#xff0c;但是Set无法保存元素添加的顺序#xff0c;
Set不允许包含相同的元素#xff0c;如果把两个相同的元素加入同一个Set中#xff0c;则添加失败#xff0…1Set集合
Set也是集合中的一个容器程序可以依次把若干个对象放进Set但是Set无法保存元素添加的顺序
Set不允许包含相同的元素如果把两个相同的元素加入同一个Set中则添加失败add()方法会返回false并且新元素不会被添加。
2HashSet
HashSet 是 Set 接口的典型实现大多数时候使用 Set 集合时就是使用这个实现类。
HashSet 按 Hash算法来存储集合中的元素因此具有很好的存取和查找性能。
特点不能保证元素的排列顺序顺序可能与添加顺序不同顺序也有可能发生变化。HashSet 不是同步的如果多个线程同时访问一个 HashSet假设有两个或者两个以上线程同时修改了HashSet集合时则必须通过代码来保证其同步。集合元素值可以是 null。当向 HashSet 集合中存入一个元素时HashSet 会调用该对象的 hashCode()方法来得到该对象的 hashCode 值然后根据该hashCode 值决定该对象在 HashSet 中的存储位置。如果有两个元素通过equals()方法比较返回 true但它们的 hashCode()方法返回值不相等HashSet 将会把它们存储在不同的位置依然可以添加成功。也就是说HashSet 集合判断两个元素相等的标准是两个对象通过 equals()方法比较相等并且两个对象的 hashCode()方法返回值也相等。
常用Api
public class Test2 { public static void main(String[] args) { SetString set new HashSet(); //添加元素 set.add(秦始皇); set.add(唐太宗); set.add(武则天); //移除元素 System.out.println(set.remove(贞观之治)); //获取元素个数 System.out.println(set.size()); //判断是否空集合 System.out.println(set.isEmpty()); // for (String s:set) { // System.out.println(s); // } // IteratorString it set.iterator(); // while (it.hasNext()){ // System.out.println(it.next()); // } set.forEach(e- System.out.println(e)); } }
public class Test { public static void main(String[] args) { SetStudent set new HashSet(); Student s1 new Student(小明,18); Student s2 new Student(小明,18); Student s3 new Student(小明,19); set.add(s1); System.out.println(set.add(s2));//false System.out.println(set.add(s3));//true
}
}
HashSet的特点可以知道HashSet中存放的元素不能重复利用这个特性就可以做一些去重的业务 输入一个字符串统计字符串中出现的字符及数量
public class HashSetDemo { public static void main(String[] args) { Scanner sc new Scanner(System.in); System.out.println(请输入字符串); String s sc.next(); char [] chars s.toCharArray(); SetCharacter set new HashSet(); MapCharacter,Integer map new HashMap(); for(int i 0;ichars.length-1;i){ if(set.add(chars[i])){ map.put(chars[i], 1); }else{ Integer k map.get(chars[i]); map.put(chars[i],k1); } } map.forEach((key,value)-System.out.println(keyvalue)); } }
重写equals 和 HashCode 方法 public class Student { public String name; public int age;
public Student(String name,int age){this.name name;this.age age;
}
Override
public boolean equals(Object o) {if (this o) return true;if (o null || getClass() ! o.getClass()) return false;Student student (Student) o;//Objects工具类下的equals和hash方法比较常用后期使用较多return age student.age Objects.equals(name, student.name);
}
Override
public int hashCode() {return Objects.hash(name, age);
}
}