java第二周

【问题描述】设A和B为两个集合,A={a,b,c,d},B={b,c,d,e},则A与B的并集为:{a,b,c,d,e,f};
A与B的差集为:{a,b};A与B的交集为:{c,d}。

  • 请编程,创建两个HashSet对象,其中保存整数。然后求它们的并集、差集和交集。

提示:利用addAll()、removeAll()、retainAll()方法。
【输入形式】

  • 第1行是第1个HashSet对象的元素,0 表示结束
  • 第2行是第2个HashSet对象的元素,0 表示结束

【输出形式】

  • 两个集合的并集中的元素,用空格分隔
  • 两个集合的差集中的元素,用空格分隔
  • 两个集合的交集中的元素,用空格分隔

【样例输入】

  • 1 2 3 4 0
  • 3 4 5 6 0
    【样例输出】
  • 1 2 3 4 5 6
  • 1 2
  • 3 4
package 实验作业_集合2;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ice_water
 * @Date: 2022/03/11/3:26 PM
 */

import java.util.*;

public class demo01 {
  public static void main(String[] args) {
    HashSet<Integer> result = new HashSet<>();
    HashSet<Integer> A = new HashSet<>();
    HashSet<Integer> B = new HashSet<>();


    Scanner scanner = new Scanner(System.in);


    while (scanner.hasNext()) {
      int element = scanner.nextInt();
      if (element == 0) {
        break;
      } else {
        A.add(element);
      }
    }

    while (scanner.hasNext()) {
      int element = scanner.nextInt();
      if (element == 0) {
        break;
      } else {
        B.add(element);
      }
    }


    result.addAll(A);

    result.addAll(B);
    String re1 = result.toString().replace("[", "").replace("]", "").replace(",", "");
    System.out.println(re1);

    result.addAll(A);

    result.removeAll(B);
    String re3 = result.toString().replace("[", "").replace("]", "").replace(",", "");
    System.out.println(re3);


    result.addAll(A);

    result.retainAll(B);
    String re2 = result.toString().replace("[", "").replace("]", "").replace(",", "");
    System.out.println(re2);
  }

}

package 实验作业_集合2;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ice_water
 * @Date: 2022/03/11/3:52 PM
 */

import java.util.*;

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

    set.add("Hello");
    set.add("World");
    set.add("HaHaHaHaHa");

    //1.用增强型for循环进行遍历
    for (String str : set) {
      System.out.println(str);
    }

    //2.把set转换为数组,然后用普通for循环进行遍历
    String[] strArray = new String[set.size()];
    set.toArray(strArray);
    for (int i = 0; i < strArray.length; i++)
      System.out.println(strArray[i]);

    //3.用Iterator迭代器进行遍历
    Iterator<String> it = set.iterator();
    while ( it.hasNext()
    ) {
      String str = it.next();
      System.out.println(str);
    }
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值