美文网首页
Java ArrayList类

Java ArrayList类

作者: SnailLi | 来源:发表于2019-06-10 15:41 被阅读0次

    好记性不如烂笔头之:Java ArrayList类的一些使用方法

    package cn.sl.arrayList.ui;
    import java.util.*;
    import java.util.function.Predicate;
    /**
     * Created by snailLi on 2019/6/6
     *
     * @description: ArrayList类的使用
     */
     public class Test {
    
     /**
      * ArrayList就是传说中的动态数组,用MSDN中的说法,就是Array的复杂版本,它提供了如下一些好处:
      * 动态的增加和减少元素
      * 实现了ICollection和IList接口
      * 灵活的设置数组的大小
      */
    
      public static void main(String[] args) {
        int[] array = new int[]{6,6,5,9,3,5,96,46,25,68,5,9,9,354,26,26,54,23,9,872,2,5,654,32,5};
        Test.addArray(array);
    
        Test.addArray();
    
        Test.remove();
    
        Test.conversion();
    
        Test.sort();
    
        Test.operation();
      }
    
      /**
       * ArrayList动态添加元素
       * 方法:add()
       *
       * */
       public static void addArray (int[] array){
        /**
         * Appends the specified element to the end of this list.
         *
         * 将指定的元素追加到此列表的末尾。
         * */
           ArrayList oddList = new ArrayList();//奇数
           ArrayList evenList = new ArrayList();//偶数
           for (int j : array) {
              //奇数 偶数
              if (j % 2 ==0){
                  evenList.add(j);
              }
              else {
                  oddList.add(j);
             }
         }
          System.out.println("将指定的元素追加到此列表的末尾:\n" + "奇数列表:" + oddList + "\n" + "偶数列表:" + evenList);
    
        /**
         * Inserts the specified element at the specified position in this list.
         * Shifts the element currently at that position (if any) and any
         * subsequent elements to the right (adds one to their indices).
         *
         * 将指定元素插入列表中的指定位置。将当前位于该位置的元素(如果有的话)和
         * 随后的任何元素向右移动(将一个元素添加到它们的索引中)。
         *
         * */
    
        ArrayList newList = new ArrayList();
        for (int j: array) {
            newList.add(j);
    
        }
        //把元素添加到指定的索引中
        newList.add(0,123);
        System.out.println("\n将一个元素添加到它们的索引中:\n" + newList);
    
        /**
         * Constructs a list containing the elements of the specified collection,
         * in the order they are returned by the collection's iterator.
         *
         *构造包含指定集合的元素的列表,按集合的迭代器返回元素的顺序排列。
         *
         * */
        ArrayList list = new ArrayList(Arrays.asList(array,array));
        System.out.println("\n构造包含指定集合的元素的列表,按集合的迭代器返回元素的顺序排列:\n" + list);
    
    }
    
    /**
     *插入元素
     */
    public static void addArray (){
    
        ArrayList<String> list = new ArrayList<String>();
        list.add("a");
        list.add("c");
        list.add("d");
        list.add("e");
        System.out.println(list + "\n");
    
        ArrayList<String> array = new ArrayList<String>();
        array.add("b");
    
        /**
         * 将集合中的某个元素插入ArrayList的指定索引处--addAll(int index, CollectionE> c);
         */
        list.addAll(1,array);
        System.out.println("将集合中的某个元素插入ArrayList的指定索引处:" + list + "\n");
    
    
        ArrayList<String> newList = new ArrayList<String>();
        newList.add("f");
        /**
         * 将集合中的某个元素插入ArrayList的最后面---addAll(Collection<? extends E> c);
         */
        list.addAll(newList);
        System.out.println("将集合中的某个元素插入ArrayList的最后面:" + list);
    
    
    }
    
    
    /**
     * 删除元素
     * @return
     */
    public static void remove (){
    
        ArrayList<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");
        System.out.println(list + "\n");
    
        /**
         * 从ArrayList中移除特定对象的第一个匹配项,注意是第一个-- remove(Object o)
         */
        list.remove("b");
        System.out.println("从ArrayList中移除特定对象的第一个匹配项:\n" + list + "\n");
    
    
        /**
         * 移除ArrayList的指定索引处的元素--remove(int index);
         */
        list.remove(list.size()-1);
        System.out.println("移除ArrayList的指定索引处的元素:\n" + list);
    
        /**
         * 从该列表中删除指定集合中包含的所有元素--removeAll(Collection<?> c)
         */
        ArrayList<String> newList = new ArrayList<String>();
        newList.add("a");
        newList.add("b");
        list.removeAll(newList);
        System.out.println("从该列表中删除指定集合中包含的所有元素:\n" + list);
    
        /**
         * 删除列表所有元素
         */
        list.clear();
        System.out.println("删除列表所有元素:\n" + list);
    
    
        /**
         * 过滤特定的元素
         */
        ArrayList<String> list2 = new ArrayList<>();
        list2.add("张三");
        list2.add("李四");
        list2.add("王二");
        list2.add("李麻子");
        list2.add("刘三");
        list2.removeIf(obj-> {
            return obj.contains("李") || obj.contains("张");
        });
        System.out.println("\n过滤特定元素:" + list2);
    
        ArrayList<Integer> list3 = new ArrayList<>();
        Random r = new Random(1);
        for (int i = 0; i < 50; i++) {
            Integer in = r.nextInt(100);
            list3.add(in);
        }
        System.out.println("\n过滤特定元素:" + list3);
        list3.removeIf(obj-> {
            return obj % 2 ==0;
        });
        System.out.println("\n过滤特定元素:" + list3);
    
    }
    
    /**
     * List转换为数组&&数组转换为List
     */
    public static void conversion(){
    
        ArrayList<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");
        System.out.println(list + "\n");
    
    
        /**
         * Returns an array containing all of the elements in this list in proper sequence
         * (from first to last element); the runtime type of the returned array is that of
         * the specified array.  If the list fits in the specified array, it is returned therein.
         * Otherwise, a new array is allocated with the runtime type of the
         * specified array and the size of this list.
         *
         * 返回一个数组,该数组包含列表中按正确顺序排列的所有元素
         * (从第一个元素到最后一个元素);返回数组的运行时类型是指定数组的运行时类型。
         * 如果列表符合指定的数组,则返回其中的列表。
         * 否则,将使用指定数组的运行时类型和该列表的大小分配一个新数组。
         */
        String[] stringArray = list.toArray(new String[list.size()]);
     //        错误方式:使用String[] 强转会出现ClassCastException (类转换异常)
    //        String[] stringArray = (String[]) list.toArray();
        System.out.println("List转换为数组--<T> T[] toArray(T[] a):\n" + Arrays.toString(stringArray));
    
    
        /**
         * Returns an array containing all of the elements in this list in proper
         * sequence (from first to last element).
         *
         * 返回一个数组,该数组按适当的顺序(从第一个元素到最后一个元素)包含列表中的所有元素。
         */
        Object[] obj = list.toArray();
        System.out.println("List转换为数组--Object[] toArray():\n" + Arrays.toString(obj));
    
    
        String[] string = {"a","b","c","d"};
        /**
         * Returns a fixed-size list backed by the specified array.  (Changes to the returned list
         * "write through" to the array.)  This method acts as bridge between array-based
         * and collection-based APIs, in combination with {@link Collection#toArray}.
         * The returned list is serializable and implements {@link RandomAccess}.
         *
         * 返回指定数组支持的固定大小列表。(对返回列表“write through”到数组的更改。)
         * 此方法与{@link Collection#toArray}结合,充当基于数组和基于集合的api之间的桥梁。
         * 返回的列表是可序列化的,并实现{@link RandomAccess}。
         */
        List<String> stringList = Arrays.asList(string);
    //        注意的是:返回的集合我们不能对其增删元素,否则会抛出异常,并且对集合的元素进行修改会影响数组对应的元素。
    //        stringList.add("e");
        System.out.println("数组转换为List--<T> List<T> asList(T... a):\n" + stringList);
    
    
        List<String> newStringList = new ArrayList<String>();
        /**
         * Appends all of the elements in the specified collection to the end of this list,
         * in the order that they are returned by the specified collection's iterator (optional operation).
         * The behavior of this operation is undefined if the specified collection is modified while the
         * operation is in progress.  (Note that this will occur if the specified
         * collection is this list, and it's nonempty.)
         *
         * 将指定集合中的所有元素按照指定集合的迭代器(可选操作)返回的顺序追加到此列表的末尾。
         * 如果在操作进行期间修改了指定的集合,则此操作的行为未定义。
         * (注意,如果指定的集合是这个列表,并且它不是空的,则会发生这种情况。)
         */
        newStringList.addAll(Arrays.asList(string));
        System.out.println("数组转换为List--boolean addAll(Collection<? extends E> c):\n" + newStringList);
    
    
    }
    
    /**
     * 排序
     */
    public static void sort(){
        ArrayList<Integer> list = new ArrayList<Integer>();
        /**
         * 生成10个1到100以内的随机数
         */
        Random r = new Random(1);
        for (int i = 0; i < 10; i++) {
            Integer in = r.nextInt(100);
            list.add(in);
        }
        System.out.println("生成10个1到100以内的随机数集合:\n" + list);
        Collections.sort(list);
        System.out.println("升序:\n" + list);
    
        Collections.sort(list,Collections.reverseOrder());
        System.out.println("降序:\n" + list);
    
        /**
         * 最大的数&&最小的数
         */
        int mun = Collections.max(list);
        int mun1 = Collections.min(list);
        System.out.println("list列表:\n" + list + "\n最大的数是:" + mun  + "\n最小的数是:" + mun1);
    
    
        /**
         *Collections的sort方法是对集合元素进行自然排序,那么两个元素对象之间就一定要有大小之分。
         * 这个大小之分是如何界定的?实际上,在使用Collections的sort排序的集合元素都必须是Comparable接口的实现类,
         * 该接口表示其子类是可比较的,因为实现该接口必须重写抽象方法:
         * int compareTo(T t);
         * 该方法用于使当前对象与给定对象进行比较。
         * 若当前对象大于给定对象,那么返回值应为>0的整数。
         * 若小于给定对象,那么返回值应为<0的整数。
         * 若两个对象相等,则应返回0。
         * Comparator接口
         * 一旦Java类实现了Comparable接口,其比较逻辑就已经确定,如果希望在排序的操作中临时指定比较规则,可以采用Compartor接口回调的范式。
         * Comparator接口要求实现类必须重写其定义的方法: int compare(T o1,T o2);
         * 该方法的返回值要求:
         * 若o1>o2,则返回值应>0;
         * 若o1<o2,则返回值应<0;
         * 若o1=o2,则返回值应=0。
         *
         */
    
    }
    
    
    public static void operation(){
    
        ArrayList<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");
        list.add("b");
        System.out.println(list + "\n");
    
        /**
         * 如果list含有元素o,返回true
         */
        String string = "b";
        if (list.contains(string)){
            System.out.println("\nlist集合包含元素" + string);
        }
        else {
            System.out.println("\nlist集合不包含元素" + string);
        }
    
        /**
         * list是否包含元素
         */
        if (list.isEmpty()){
            System.out.println("\nlist集合不包含任何元素");
        }
        else {
            System.out.println("\nlist集合包含至少一个元素元素");
        }
    
    
        /**
         * 返回指定index处的元素
         */
        int index = 2;
        String str = list.get(index);
        System.out.println("\nlist列表的第" + index + "个索引下的元素为:" + str);
    
        /**
         *获取list中第一个匹配元素的index
         */
        int index1 = list.indexOf(string);
        System.out.println("\n获取list中第一个匹配元素" + string + "的下标为:" + index1);
        /**
         * 获取list中最后一个匹配元素的index
         */
        int index2 = list.lastIndexOf(string);
        System.out.println("\n获取list中最后一个匹配元素" + string + "的下标为:" + index2);
    
    
    
        /**
         * 替换指定index(下标)处的元素
         */
        String replace = "3";
        String s = list.set(index,replace);
        System.out.println("\n替换list列表第" + index +"个下标的元素为:" + replace + ",新列表为:" + list);
    
        /**
         * 替换指定的元素
         */
        Collections.replaceAll(list,"3","c");
        System.out.println("\n替换指定的元素3为c:" + list);
    
    
    }
    
    
    
    }

    相关文章

      网友评论

          本文标题:Java ArrayList类

          本文链接:https://www.haomeiwen.com/subject/ynvzxctx.html