Collection的几个方法

 

Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
Collection coll1 = new ArrayList();
coll1.add(123);
coll.removeAll(coll1);
System.out.println(coll);

 

  • removeAll(Collection coll1)
  • 移除集合coll1中所有在coll中出现的元素
  • 输出结果应该[456]
  • ——————————————————
    Collection coll = new ArrayList();
    coll.add(123);
    coll.add(456);
    Collection coll1 = new ArrayList();
    coll1.add(456);
    coll.retainAll(coll1);
    System.out.println(coll);

     

  • retrainAll()
  • 修改当前集合,将当前结果变为coll1和coll2公共的元素(取交集)
  • 输出结果应该[456]
  • ———————————————————
    1 Collection coll = new ArrayList();
    2 coll.add(456);
    3 Collection coll1 = new ArrayList();
    4 coll1.add(456);
    5 System.out.println(coll.equals(coll1));

     

  • equals(Object obj)
  • 比较两个集合是否相同
  • 输出结果应该true
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        Object[] objects = coll.toArray();
  • 集合→数组
    List objects1 = Arrays.asList(objects);

 

  • 数组→集合
        List ints = Arrays.asList(new int[]{123, 456});
        System.out.println(ints);
        //输出:[[I@28d93b30]
        List ints1 = Arrays.asList(new Integer[]{123, 456});
        System.out.println(ints1);
        //输出:[123, 456]    
  • 调用Arrays.asList时,要使用包装类。

 

posted @ 2021-12-07 15:23  Boerk  阅读(83)  评论(0)    收藏  举报