Java 数据结构 - 集合的加法
Set 接口提供了一个名为 addAll() 的方法(继承自 Collection 接口),使用此方法可以将一个集合的内容添加到另一个集合中。
示例
import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class AddingTwoSets { public static void main(String args[]) { Set set1 = new HashSet(); set1.add(100); set1.add(501); set1.add(302); set1.add(420); System.out.println("Contents of set1 are: "); System.out.println(set1); Set set2 = new HashSet(); set2.add(200); set2.add(630); set2.add(987); set2.add(665); System.out.println("Contents of set2 are: "); System.out.println(set2); set1.addAll(set2); System.out.println("Contents of set1 after addition: "); System.out.println(set1); } }
输出
Contents of set1 are: [100, 420, 501, 302] Contents of set2 are: [630, 200, 665, 987] Contents of set1 after addition: [100, 420, 501, 630, 200, 665, 987, 302]
广告