59.md 11.1 KB
Newer Older
W
wizardforcel 已提交
1
# Java `HashSet`示例
W
init  
wizardforcel 已提交
2 3 4

> 原文: [https://javatutorial.net/java-hashset-example](https://javatutorial.net/java-hashset-example)

W
wizardforcel 已提交
5
使用哈希表进行存储的集合通常由 Java `HashSet`类创建。 顾名思义,`HashSet`实现`Set`接口,并且还使用一个哈希表,该哈希表是`HashMap`实例。`HashSet`中元素的顺序是随机的。 此类允许使用`null`元素。 就复杂度而言,`HashSet`为基本操作(如添加,删除,包含和大小)提供恒定的时间性能,前提是假定元素已被函数正确分散。
W
init  
wizardforcel 已提交
6 7 8

![java-featured-image](img/e0db051dedc1179e7424b6d998a6a772.jpg)

W
wizardforcel 已提交
9
## 有关`HashSet`的重要信息
W
init  
wizardforcel 已提交
10

W
wizardforcel 已提交
11 12 13 14 15 16 17
*   `HashSet`通过使用称为**散列**的机制来存储元素。
*   `HashSet`中不能存在重复的元素。
*   `HashSet`允许为空值。
*   `HashSet`类不同步。
*   `HashSet`的顺序不由插入顺序维护。 元素(在此类中)是根据其哈希码插入的。
*   就搜索操作而言,由于`HashSet`具有恒定的时间复杂度,因此它是最好的方法。
*   `HashSet`的初始默认容量为 16,而负载系数为 0.75。
W
init  
wizardforcel 已提交
18

W
wizardforcel 已提交
19
## `HashSet`简单的结构图
W
init  
wizardforcel 已提交
20 21 22

![hashset in java](img/8d88c8914494e655c806585a31c797f3.jpg)

W
wizardforcel 已提交
23
Java 中的`HashSet`
W
init  
wizardforcel 已提交
24

W
wizardforcel 已提交
25
我们放入`HashMap`中的每个对象都首先通过哈希算法发送。 该算法的唯一目的是为传递给它的每个对象生成一个称为**哈希**的唯一编号。 在上图中,此算法为字符串`Lisa Morgan`生成了数字 3,为`Bob Wiliams`生成了数字 2,为`Jane Smith`生成了数字 1。 以后,这些数字将作为索引存储在数组中。 每当您要对`HashSet`中的元素执行任何类型的操作时,您都将通过由哈希算法生成的索引来解决它们。 这就是`HashSet`以随机顺序返回元素的原因。 哈希号是`HashSet`知道的唯一顺序。
W
init  
wizardforcel 已提交
26

W
wizardforcel 已提交
27
## `HashSet`中的构造方法
W
init  
wizardforcel 已提交
28

W
wizardforcel 已提交
29
1.  `HashSet hashSet = new HashSet();`
W
wizardforcel 已提交
30 31 32
2.  `HashSet hashSet = new HashSet(int initialCapacity);`
3.  `HashSet hashSet = new HashSet(int initialCapacity, float loadFactor);`
4.  `HashSet hashSet = new HashSet(Collection c);`
W
init  
wizardforcel 已提交
33

W
wizardforcel 已提交
34
这些构造函数之间的主要区别在于,在 #1 构造函数中,初始容量为 16,默认负载因子为 0.75,但在 #2 中,您实际上可以设置容量。 负载系数的默认值仍为 0.75。 在构造函数 3 中,您可以设置容量和负载系数。
W
init  
wizardforcel 已提交
35

W
wizardforcel 已提交
36
## `HashSet`类中的方法
W
init  
wizardforcel 已提交
37

W
wizardforcel 已提交
38 39 40 41 42 43 44 45
1.  `boolean add(Object o)`:用于添加作为参数提供的元素,如果不存在,则返回`false`
2.  `void clear()`:用于删除所有元素。
3.  `boolean contains(Object o)`:如果指定的`Object``HashSet`中,则返回`true`;否则,返回`false`
4.  `boolean remove(Object o)`:用于从`HashSet`中删除指定的`Object`(如果存在)。
5.  `Iterator iterator()`:用于返回集合中元素上的迭代器。
6.  `boolean isEmpty()`:用于检查`HashSet`是否为空。 如果为空,则返回`true`;否则为`false`
7.  `int size()`:返回集合的大小。
8.  `Object clone()`:创建集合的副本。
W
init  
wizardforcel 已提交
46 47 48

有关所有方法的文档,请访问 [Oracle 官方文档页面](https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html)

W
wizardforcel 已提交
49
### 使用`add()`在`HashSet`中添加元素
W
init  
wizardforcel 已提交
50

W
wizardforcel 已提交
51
语法:`HashSet.add(Object o);`
W
init  
wizardforcel 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

```java
import java.io.*; 
import java.util.HashSet; 

public class HashSetExample { 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<String> animals = new HashSet<String>(); 

        animals.add("Elephant"); 
        animals.add("Tiger"); 
        animals.add("Lion"); 

        // Displaying the HashSet 
        System.out.println("HashSet: " + animals); 
    } 
}
```

W
wizardforcel 已提交
73
**输出**
W
init  
wizardforcel 已提交
74 75 76 77 78

```java
HashSet: [Elephant, Tiger, Lion]
```

W
wizardforcel 已提交
79
### 使用`clear()`清空`HashSet`
W
init  
wizardforcel 已提交
80

W
wizardforcel 已提交
81
语法:`HashSet.clear();`
W
init  
wizardforcel 已提交
82

W
wizardforcel 已提交
83
**输出**
W
init  
wizardforcel 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

```java
import java.io.*; 
import java.util.HashSet; 

public class HashSetExample{ 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<String> animals = new HashSet<String>(); 

        animals.add("Elephant"); 
        animals.add("Tiger"); 
        animals.add("Lion"); 

        // Displaying the HashSet 
        System.out.println("HashSet: " + animals); 

        // Clearing the hash set
        animals.clear(); 

        // Displaying the final Set after clearing; 
        System.out.println("The final set: " + animals); 
    } 
}
```

```java
HashSet: [Elephant, Tiger, Lion]
The final set: []
```

W
wizardforcel 已提交
116
### 使用`contains()`检查`HashSet`中是否存在元素
W
init  
wizardforcel 已提交
117

W
wizardforcel 已提交
118
语法:`Hash_Set.contains(Object o)`
W
init  
wizardforcel 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

```java
import java.io.*; 
import java.util.HashSet; 

public class HashSetExample { 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<String> animals = new HashSet<String>(); 

        animals.add("Elephant"); 
        animals.add("Tiger"); 
        animals.add("Lion"); 

        // Displaying the HashSet 
        System.out.println("HashSet: " + animals); 

        // Checking for "Lion" in the hash set
        System.out.println("Does the HashSet contain 'Lion'? " + animals.contains("Lion")); 

        // Checking for "Elephant" in the hash set
        System.out.println("Does the HashSet contain 'Elephant'? " + animals.contains("Elephant")); 

        // Checking for "Tiger" in the hash set
        System.out.println("Does the HashSet contain 'Tiger'? " + animals.contains("Tiger")); 

        // Checking for "Chicken" in the hash set 
        System.out.println("Does the HashSet contain 'Chicken'? " + animals.contains("Chicken")); 
    } 
}
```

W
wizardforcel 已提交
152
**输出**
W
init  
wizardforcel 已提交
153 154 155 156 157 158 159 160 161

```java
HashSet: [Elephant, Tiger, Lion]
Does the Set contain 'Lion'? true
Does the Set contain 'Elephant? true
Does the Set contain 'Tiger'? true
Does the Set contain 'Chicken'? false
```

W
wizardforcel 已提交
162
### 使用`remove()`从`HashSet`中删除元素
W
init  
wizardforcel 已提交
163

W
wizardforcel 已提交
164
语法:`HashSet.remove(Object o)`
W
init  
wizardforcel 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

```java
import java.util.*; 
import java.util.HashSet; 

public class HashSetExample { 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<String> animals = new HashSet<String>(); 

        animals.add("Elephant"); 
        animals.add("Tiger"); 
        animals.add("Lion"); 

        // Displaying the HashSet 
        System.out.println("HashSet: " + animals); 

        set.remove("Elephant"); 
        set.remove("Lion"); 

        // Displaying the HashSet after removal 
        System.out.println("HashSet after removing elements: " + animals); 
    } 
}
```

W
wizardforcel 已提交
192
**输出**
W
init  
wizardforcel 已提交
193 194 195 196 197 198

```java
HashSet: [Elephant, Tiger, Lion]
HashSet after removing elements: [Tiger]
```

W
wizardforcel 已提交
199
### `Iterator()`方法
W
init  
wizardforcel 已提交
200

W
wizardforcel 已提交
201
语法:`Iterator iterator = HashSet.iterator()`;
W
init  
wizardforcel 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

```java
import java.util.*; 
import java.util.HashSet; 

public class HashSetExample { 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<String> animals = new HashSet<String>(); 

        animals.add("Elephant"); 
        animals.add("Tiger"); 
        animals.add("Lion"); 

        // Displaying the HashSet 
        System.out.println("HashSet: " + animals); 

        // Creating an iterator 
        Iterator iterator = animals.iterator(); 

        // Displaying the values after iterating through the set 
        System.out.println("The iterator values are: "); 
        while (iterator.hasNext()) { 
            System.out.println(iterator.next()); 
        } 
    } 
}
```

W
wizardforcel 已提交
232
**输出**
W
init  
wizardforcel 已提交
233 234 235 236 237 238 239 240 241

```java
HashSet: [Elephant, Tiger, Lion]
The iterator values are: 
Elephant
Tiger
Lion
```

W
wizardforcel 已提交
242
### 使用`isEmpty()`检查`HashSet`是否为空
W
init  
wizardforcel 已提交
243

W
wizardforcel 已提交
244
语法:`HashSet.isEmpty()`;
W
init  
wizardforcel 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

```java
import java.io.*; 
import java.util.HashSet; 

public class HashSetExample { 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<String> animals = new HashSet<String>(); 

        animals.add("Elephant"); 
        animals.add("Tiger"); 
        animals.add("Lion"); 

        // Displaying the HashSet 
        System.out.println("HashSet: " + animals); 

        // Check for the empty set 
        System.out.println("Is the hash set empty: " + animals.isEmpty()); 

        set.clear(); 

        // Checking after we've cleared it out
        System.out.println("Is the hash set empty: " + animals.isEmpty()); 
    } 
}
```

W
wizardforcel 已提交
274
**输出**
W
init  
wizardforcel 已提交
275 276 277 278 279 280 281

```java
HashSet: [Elephant, Tiger, Lion]
Is the hash set empty: false
Is the hash set empty: true
```

W
wizardforcel 已提交
282
### 使用`size()`获取`HashSet`的大小
W
init  
wizardforcel 已提交
283

W
wizardforcel 已提交
284
语法:`HashSet.size()`;
W
init  
wizardforcel 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

```java
import java.util.*; 
import java.util.HashSet; 

public class HashSetExample { 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<String> animals = new HashSet<String>(); 

        animals.add("Elephant"); 
        animals.add("Tiger"); 
        animals.add("Lion"); 

        // Displaying the HashSet 
        System.out.println("HashSet: " + animals); 

        // Get the size of the hash set
        System.out.println("The size of the hash set is: " + animals.size()); 
    } 
}
```

W
wizardforcel 已提交
309
**输出**
W
init  
wizardforcel 已提交
310 311 312 313 314 315

```java
HashSet: [Elephant, Tiger, Lion]
The size of the hash set is: 3
```

W
wizardforcel 已提交
316
### 使用`clone()`克隆`HashSet`
W
init  
wizardforcel 已提交
317

W
wizardforcel 已提交
318
语法:`HashSet.clone()`
W
init  
wizardforcel 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

```java
import java.io.*; 
import java.util.HashSet; 

public class HashSetExample { 
    public static void main(String args[]) 
    { 
        // Creating an empty HashSet 
        HashSet<String> animals = new HashSet<String>(); 

        animals.add("Elephant"); 
        animals.add("Tiger"); 
        animals.add("Lion"); 

        System.out.println("HashSet: " + animals); 

        // Creating a new set
        HashSet clonedSet = new HashSet(); 

        // Cloning the set using clone() method 
        clonedSet = (HashSet)animals.clone(); 

        // Displaying the new hashset; 
        System.out.println("The new set: " + clonedSet); 
    } 
}
```

W
wizardforcel 已提交
348
**输出**
W
init  
wizardforcel 已提交
349 350 351 352 353 354

```java
HashSet: [Elephant, Tiger, Lion]
The new set: [Elephant, Tiger, Lion]
```

W
wizardforcel 已提交
355
## 如何迭代`HashSet`
W
init  
wizardforcel 已提交
356

W
wizardforcel 已提交
357
有两种方法可以遍历`HashSet`
W
init  
wizardforcel 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

*   使用迭代器
*   不使用迭代器

**1)使用迭代器**

```java
import java.util.HashSet;
import java.util.Iterator;

class IterateHashSetExample{ 
  public static void main(String[] args) {
     HashSet<String> animals= new HashSet<String>();

     //add elements to HashSet
     animals.add("Elephant");
     animals.add("Tiger");
     animals.add("Lion");

     Iterator<String> iterator = animals.iterator();
     while(iterator.hasNext()){
        System.out.println(iterator.next());
     }
  }
}
```

上面的代码只是将迭代器“附加”到动物散列集上,然后仅打印每一个迭代器,直到没有更多为止。 另外,此方法将忽略重复项。 如果有重复项,则重复项仅打印一次。

W
wizardforcel 已提交
387
**输出**
W
init  
wizardforcel 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

```java
Elephant
Tiger
Lion
```

**2)不使用迭代器**

```java
import java.util.HashSet;
import java.util.Set;

class IterateHashSetExample{ 
  public static void main(String[] args) {
     Set<String> animals = new HashSet<String>();

     //add elements to HashSet
     animals.add("Elephant");
     animals.add("Tiger");
     animals.add("Lion");

     for (String animal : animals) {
        System.out.println(animal);
     }
  }
}
```

W
wizardforcel 已提交
417
**输出**
W
init  
wizardforcel 已提交
418 419 420 421 422 423

```java
Elephant
Tiger
Lion
```