当前位置: 代码迷 >> 综合 >> java自学笔记:Set类(1)HashSet
  详细解决方案

java自学笔记:Set类(1)HashSet

热度:34   发布时间:2023-12-07 03:19:13.0

Set接口继承Collection接口,但是Set限定其元素不可重复

AbstractSet继承AbstractCollection,AbstractSet为equals和hashCode提供实例,但是没有size和iterator的实例,因而为抽象类

Set类三大实体类为HashSet LinkedHashSet TreeSet

HashSet:
默认HashSet长度16,负载系数0.75.负载系数为在容量达到该百分比时容量会扩大一倍。更高的负载系数可以减少内存浪费,但是会增加搜索时间,0.75是一个较好的平衡值

package chapter21;import java.util.*;public class TestHashSet {
    public static void main(String[] args) {
    // TODO Auto-generated method stub//Create a hash setSet<String> set = new HashSet<String>();//Add strings to the setset.add("London");set.add("Paris");set.add("New York");set.add("San Francisco");set.add("Beijing");set.add("New York");System.out.println(set);for (String s : set) {
    System.out.print(s + " ");}}}

New York在本例中添加了两次,但是只有一个储存下来,因为set不允许重复

HashSet储存元素的顺序不一定和输入顺序一致,而是完全随机。LinkedHashSet可以按顺序储存

Set是Collection的实例,因此Collection类所有方法也可以应用于Set,如下例应用了add remove contains size addAll removeAll retainAll等方法

package chapter21;import java.util.*;public class TestMethodsInCollection {
    public static void main(String[] args) {
    // TODO Auto-generated method stub//create set1Set<String> set1 = new HashSet<String>();//add strings to set1set1.add("London");set1.add("Paris");set1.add("New York");set1.add("San Francisco");set1.add("Beijing");System.out.println("set1: " + set1);System.out.println(set1.size() + " elements in set1");//delete a string from set1set1.remove("London");System.out.println("set1: " + set1);System.out.println(set1.size() + " elements in set1");//create set2Set<String> set2 = new HashSet<String>();//add strings to set2set2.add("London");set2.add("Shanghai");set2.add("Paris");System.out.println("set2: " + set2);System.out.println(set2.size() + " elements in set2");System.out.println("Is Taipei in set2? " + set2.contains("Taipei"));set1.addAll(set2);System.out.println("adding set2 to set1, set1 is " + set1);set1.removeAll(set2);System.out.println("removing set2 from set1, set1 is " + set1);set1.retainAll(set2);System.out.println("removing common elements in set2 from set1 " + set1);}}
  相关解决方案