zoukankan      html  css  js  c++  java
  • collections方法记录

    1.addAll()方法:往集合中添加一些元素

                    格式:public static <T> boolean addAll(Collection<T> c,T... elements)

    代码演示:

    //演示集合中的方法
    public class CollectionsDemo {
        public static void main(String[] args) {
            List<String> list=new ArrayList<String>() ;
            list.add("Icey");
            Collections.addAll(list,"aaa","bb","c");
            System.out.println(list);
        }
    }

    运行结果:

    2.shuffle()方法:打乱集合顺序

                     格式:public static void  shuffle(List<?> list)

    代码演示:

    //打乱顺序shuffle()方法
    Collections.shuffle(list);
    System.out.println(list);

    运行结果:

    3.sort()方法:按照Comparator指定的规则给集合中的元素排序

                格式:public static <T> void sort(List<T> list, Comparator<? super T>)

    注意:

    (1)sort方法默认为升序

    (2)升序:return 前一个参数.变量 - 后一个参数.变量;

    (3)降序:return 后一个参数.变量 - 前一个参数.变量;

    (4)当两个变量值相同时,默认谁先加入集合,谁就排在前面。

    若:年龄相同时,比较名字的首字母升序:return this.getName().charAt(0)-o.getName().charAt(0);

     代码演示:

    import java.util.*;
    
    public class Demo3 {
        public static void main(String[] args) {
            List<Person> list2=new ArrayList<>();
            Person p1=new Person(18,"Icey","female");
            Person p2=new Person(19,"Shane","male");
            Person p3=new Person(22,"Amda","female");
            Person p4=new Person(15,"maxy","male");
            Person p5=new Person(18,"luxy","male");
            Collections.addAll(list2,p1,p2,p3,p4,p5);
            Collections.sort(list2, new Comparator<Person>() {
                @Override
                public int compare(Person person, Person t1) {
                    //按照年龄升序排序
                    if (person.getAge() != t1.getAge()) {
                        return person.getAge() - t1.getAge();
                    } else {
                        //如果年龄相同,就按照名字首字母降序排序
                        return t1.getName().charAt(0)-person.getName().charAt(0);
                    }
                }
            });
            System.out.println(list2);
        }
    }

    运行结果:

    [Person{age=15, name='maxy', gender='male'}, Person{age=18, name='luxy', gender='male'}, Person{age=18, name='Icey', gender='female'},

    Person{age=19, name='Shane', gender='male'}, Person{age=22, name='Amda', gender='female'}]

  • 相关阅读:
    ADB命令大全
    Backup your Android without root or custom recovery -- adb backup
    Content portal for Pocketables Tasker articles
    Is there a way to detect if call is in progress? Phone Event
    Tasker to proximity screen off
    Tasker to detect application running in background
    Tasker to create toggle widget for ES ftp service -- Send Intent
    Tasker to proximity screen on
    Tasker to answer incoming call by pressing power button
    Tasker to stop Poweramp control for the headset while there is an incoming SMS
  • 原文地址:https://www.cnblogs.com/iceywu/p/12040404.html
Copyright © 2011-2022 走看看