zoukankan      html  css  js  c++  java
  • java中Collection和collections的区别

    1、Collection是java.util中的一接口,他提供了对集合对象进行基本操作的通用接口方法。Collection接口在java类库中有很多具体的实现。Collection接口的意义是为各种具体的集合提供了最大化的统一操作方式,其直接继承接口LIst与Set。

    Collection(

    List(LinkedLIst,ArrayList,Vector),

    set(hashSet,treeSet)

    2、Collection则是集合类的一个工具类或者是帮助类,提供给了一系列的静态方法,用于对集合中元素进行排列、搜索以及线程安全等各种操作。

    1)排序(sort)

      使用sort方法可以根据元素的自然顺序,对指定列表按升序进行排序。列表中的所有元素必须实现Comparable接口。此列表内的所有元素都必须是使用指定比较器互相比较的。

    List<Integer> list = new ArrayList<Integer>();
            int array[] = {112, 111, 23, 456, 231 };
            for (int i = 0; i < array.length; i++) {
                list.add(array[i]);
            }
            Collections.sort(list);
            for (int i = 0; i < array.length; i++) {
                System.out.println(list.get(i));
            }
    

     2)复制(copy)

              //定义一个list
    		List<Integer> list=new ArrayList<Integer>();
    		
    		Integer math[]={23,34,432,23,43,12,23,32};
    		
    		
    		for(int i=0;i<math.length;i++){
    			list.add(math[i]);
    		}
    		//新的list
    		List<Integer> lists=new ArrayList<Integer>(Arrays.asList(new Integer[list.size()]));
    		System.out.println(list);
    		//copy(被赋值的在前,是在后)
    		Collections.copy(lists,list);
    		System.out.println(lists.size());
    		for (Integer integer : lists) {
    			System.out.print(integer+",");
    		}
    

      3)混排(Shuffling)

    混排算法所做的正好与 sort 相反: 它打乱在一个 List 中可能有的任何排列的踪迹。也就是说,基于随机源的输入重排该 List, 这样的排列具有相同的可能性(假设随机源是公正的)。这个算法在实现一个碰运气的游戏中是非常有用的。例如,它可被用来混排代表一副牌的 Card 对象的一个 List 。另外,在生成测试案例时,它也是十分有用的。

    Collections.Shuffling(list)

      4)反转(Reverse)
    使用Reverse方法可以根据元素的自然顺序 对指定列表按降序进行排序。
    Collections.reverse(list)

      5)替换所以的元素(Fill)

    使用指定元素替换指定列表中的所有元素。

    Collections.fill(li,"aaa");

      6)返回Collections中最小元素(min)
    根据指定比较器产生的顺序,返回给定 collection 的最小元素。collection 中的所有元素都必须是通过指定比较器可相互比较的
    Collections.min(list)

      7)返回Collections中最大元素(max)
    根据指定比较器产生的顺序,返回给定 collection 的最大元素。collection 中的所有元素都必须是通过指定比较器可相互比较的
    Collections.max(list)

      8) lastIndexOfSubList
    返回指定源列表中最后一次出现指定目标列表的起始位置
    int count = Collections.lastIndexOfSubList(list,li);

      9) IndexOfSubList
    返回指定源列表中第一次出现指定目标列表的起始位置
    int count = Collections.indexOfSubList(list,li);

      10) Rotate
    根据指定的距离循环移动指定列表中的元素
    Collections.rotate(list,-1);
    如果是负数,则正向移动,正数则方向移动

  • 相关阅读:
    求字符串的全排列
    不能被继承的类
    Apache2启动错误以及Ubuntu update的错误
    从尾到头输出链表
    教你在网页上加QQ链接
    UL LI P 图片加文字无缝滚动
    ASP.net 里怎么对fileUpload控件上传的文件进行管理
    表单标签
    如果我为我女朋友做了这些,她一定会娇滴滴的说:“你真坏!
    break,continue,return
  • 原文地址:https://www.cnblogs.com/story1/p/8033985.html
Copyright © 2011-2022 走看看