阿里巴巴笔试题-2个有序集合的交集

题目来自于论坛: http://topic.csdn.net/u/20081012/14/3cc93688-1f7f-4985-806c-3f729c78261b.html

不过我使用的是TreeSet,因为题目要求是集合
  1.   public static void test2() {
  2.     TreeSet<Integer> a = new TreeSet<Integer>();
  3.     TreeSet<Integer> b = new TreeSet<Integer>();
  4.     Random r = new Random();
  5.     for (int i = 0; i < 30; i++) {
  6.       a.add(r.nextInt(30));
  7.       b.add(r.nextInt(30));
  8.     }
  9.     a.retainAll(b);
  10.     System.out.println(a);
  11.     System.out.println(b);
  12.     System.out.println(a);
  13.   }
其中的 retainAll是JDK自带的算法,我们看一下源代码
  1.   public boolean retainAll(Collection<?> c) {
  2.     boolean modified = false;
  3.     Iterator<E> e = iterator();
  4.     while (e.hasNext()) {
  5.       if (!c.contains(e.next())) {
  6.         e.remove();
  7.         modified = true;
  8.       }
  9.     }
  10.     return modified;
  11.   }
我们能增强的没有啥东西了。那个modifed可以删掉,不过意义不大。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值