# Java Set集合

2018-02-20 03:02 更新

## Java集合教程 - Java Set集合

Set 表示唯一对象的集合。集合中元素的排序是不相关的。

• 数学集
• 排序集
• 导航集

## 数学集

` Set `接口对数学中的一组进行建模。集合是唯一元素的集合。

Java最多允许一个Set中的一个空元素。` Set `中元素的排序并不重要。

Java不保证` Set `中元素的排序。

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

public class Main {
public static void main(String[] args) {

Set<String> s1 = new HashSet<>();

// Create another set by copying s1
Set<String> s2 = new HashSet<>(s1);
// Add a few more elements
s2.add(null); // one null is fine

System.out.println("s1: " + s1);
System.out.println("s1.size(): " + s1.size());

System.out.println("s2: " + s2);
System.out.println("s2.size(): " + s2.size());
}
}
```

` HashSet `不保证顺序元素。` LinkedHashSet `在插入元素时保持元素顺序。

```import java.util.LinkedHashSet;
import java.util.Set;

public class Main {
public static void main(String[] args) {

}
}
```

## 集合操作

```// Union  of  s1  and  s2  will be  stored in s1

// Intersection of  s1  and  s2  will be  stored in s1
s1.retainAll(s2);

// Difference of  s1  and  s2  will be  stored in s1
s1.removeAll(s2);
```

```Set  s1Unions2  = new HashSet(s1); // Make a  copy  of  s1
```

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

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

Set<String> s2 = new HashSet<>();

System.out.println("s1: " + s1);
System.out.println("s2: " + s2);

performUnion(s1, s2);
performIntersection(s1, s2);
performDifference(s1, s2);
testForSubset(s1, s2);
}

public static void performUnion(Set<String> s1, Set<String> s2) {
Set<String> s1Unions2 = new HashSet<>(s1);
System.out.println("s1 union  s2: " + s1Unions2);
}

public static void performIntersection(Set<String> s1, Set<String> s2) {
Set<String> s1Intersections2 = new HashSet<>(s1);
s1Intersections2.retainAll(s2);
System.out.println("s1 intersection  s2: " + s1Intersections2);
}

public static void performDifference(Set<String> s1, Set<String> s2) {
Set<String> s1Differences2 = new HashSet<>(s1);
s1Differences2.removeAll(s2);

Set<String> s2Differences1 = new HashSet<>(s2);
s2Differences1.removeAll(s1);

System.out.println("s1 difference s2: " + s1Differences2);
System.out.println("s2 difference s1: " + s2Differences1);
}

public static void testForSubset(Set<String> s1, Set<String> s2) {
System.out.println("s2 is  subset s1: " + s1.containsAll(s2));
System.out.println("s1 is  subset s2: " + s2.containsAll(s1));
}

}
```

App下载