Collections

来源:互联网 发布:fragment重新加载数据 编辑:程序博客网 时间:2024/06/02 06:21

Collections

Collections:对集合操作的工具类(静态方法)----(类似)Arrays:对数字进行操作的工具类

Collections和Collection的区别?
Collection:集合:顶层次的一个根接口,有两个子接口:List,Set
Collections:对集合操作的工具类,具体的类:它针对集合进程操作!

静态方法:

    public static <T> void sort(List<T> list):默认自然排序:将集合中的元素升序排序public static <T> int binarySearch(List> list,T key):二分查找搜索法:key:查找的元素public static void reverse(List list):反转功能public static void shuffle(List<?> list):随机置换,打乱顺序

代码:

public static void main(String[] args) {    List<Integer> i = new ArrayList<Integer>();    i.add(20);    i.add(34);    i.add(36);    i.add(20);    i.add(10);    i.add(57);    i.add(67);    Collections.sort(i);    System.out.println(i);    int bs = Collections.binarySearch(i, 20);    System.out.println(bs);    Collections.reverse(i);    System.out.println(i);    Collections.shuffle(i);    System.out.println(i);} 

结果:

[10, 20, 20, 34, 36, 57, 67]
1
[67, 57, 36, 34, 20, 20, 10]
[34, 10, 36, 20, 67, 20, 57]

需求:

 创建一个集合对象,用来存储自定义对象! 并排序,比较器排序

代码:

  public static void main(String[] args) {            //创建集合对象            //list集合元素是可以重复的!            List<Student> list = new ArrayList<Student>();            //创建5个学生对象            Student s1 = new Student("高圆圆", 27) ;            Student s2 = new Student("邓超", 25) ;            Student s3 = new Student("黄晓明", 27) ;            Student s4 = new Student("刘德华", 40) ;            Student s5 = new Student("高圆圆", 27) ;            //添加到集合            list.add(s1) ;            list.add(s2) ;            list.add(s3) ;            list.add(s4) ;            list.add(s5) ;            Collections.sort(list,new Comparator<Student>(){                @Override                public int compare(Student o1, Student o2) {                    int num = o1.getAge()-o2.getAge();                    int num2 = num == 0? o1.getName().compareTo(o2.getName()): num;                    return num2;                }            });            for(Student s :list){                System.out.println(s.getName()+"~~~"+s.getAge());            }}

结果:

邓超~25
高圆圆
~27
高圆圆~27
黄晓明
~27
刘德华~~~40

需求:

模拟斗地主洗牌发牌

代码;

/*
*思路:
* 1)创建HashMap集合
* 创建ArrayList集合,来存储编号
* 2)装牌
* 给HashMap中添加编号,以及对应的牌(点色数组和花色数组遍历之后的拼接),同时
* 将编号添加ArrayList集合中
* 3)洗牌:洗的是编号
* 4)发牌:(发的也是编号,为了保证牌是有序的,所有应该用TreeSet集合)
* 5)看牌(遍历TreeSet集合获取到对应的编号,拿对应的编号在HashMap中找编号对应的牌)
* */
public class PockerTest {
public static void main(String[] args) {
HashMap