-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetsExample.java
More file actions
45 lines (31 loc) · 1.29 KB
/
Copy pathSetsExample.java
File metadata and controls
45 lines (31 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package collections;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Sets: HashSet (no guaranteed order, duplicates not allowed) and TreeSet (sorted)
*/
public class SetsExample {
private static final Logger logger = Logger.getLogger(SetsExample.class.getName());
public static void main() {
// HashSet: Generic, no duplicates allowed
Set<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Red"); // Duplicate: Will be ignored silently
logger.log(Level.INFO, "HashSet (no duplicates): {0}", colors);
logger.log(Level.INFO, "Size: {0}", colors.size());
// In MessageFormat, single quotes are escaped by doubling them (''Green'')
logger.log(Level.INFO, "Contains ''Green''?: {0}", colors.contains("Green"));
// TreeSet: Automatically keeps elements sorted in their natural order (or custom comparator)
Set<Integer> sortedNumbers = new TreeSet<>();
sortedNumbers.add(50);
sortedNumbers.add(10);
sortedNumbers.add(30);
sortedNumbers.add(20);
logger.log(Level.INFO, "TreeSet (sorted): {0}", sortedNumbers);
}
}