• 基本类型(例如:int)数组和ArrayList之间的转化


    ArrayList转化为基本类型int数组!

    import java.util.ArrayList;
    import java.util.Random;
    
    public class Main {
        public static void main(String[] args) {
            ArrayList<Integer> arrayList = new ArrayList<>();
            Random random = new Random();
            int Len = 10000;
            for (int i = 0; i < Len; i++) {
                arrayList.add(random.nextInt());
            }
            int[] ints = arrayList.stream().mapToInt(value -> 2 * value).toArray();
           } }
    IntStream mapToInt(ToIntFunction<? super T> mapper);
    参数mapper是一个函数式接口!

    ArrayList转化为包装类Interger数组!

    import java.util.ArrayList;
    import java.util.Random;

    public class Main {

    public static void main(String[] args) {
    ArrayList<Integer> arrayList = new ArrayList<>();
    Random random = new Random();
    int Len = 10000;
    for (int i = 0; i < Len; i++) {
    arrayList.add(random.nextInt());
    }
    //方式一:public Object[] toArray(){...}
    Object[] objects0 = arrayList.toArray();//方式一
    //方式二:public <T> T[] toArray(T[] a){...}
    Integer[] integers1 = arrayList.toArray(new Integer[arrayList.size()]);
    Integer[] integers2 = arrayList.toArray(new Integer[0]);
    //对比public Object[] toArray(){...} public <T> T[] toArray(T[] a){...}源码
    //推荐方式
    Integer[] integers3 = (Integer[]) arrayList.toArray();
    }
    }

    基本类型数组转ArrayList!

    public class Main {
    
        public static void main(String[] args) {
            int[] array = new int[10000000];
            Random random = new Random();
            for (int  i = 0;  i < array.length;  i++) {
                array[i] = random.nextInt();
            }
    int cycle = 100; long begin = 0; long end = 0;
         //方式1 begin
    = System.currentTimeMillis(); for (int i = 0; i < cycle; i++) { List<Integer> collect1 =new ArrayList<>(array.length); for (int k = 0; k < array.length; k++) { collect1.add(array[k]); } collect1 = null; } end = System.currentTimeMillis(); System.out.printf("(end - begin)*1.0/cycle:%.6f ",(end - begin)*1.0/cycle);      //方式2  begin = System.currentTimeMillis(); for (int i = 0; i < cycle; i++) { List<Integer> collect0 = Arrays.stream(array).boxed().collect(Collectors.toList()); collect0 = null; } end = System.currentTimeMillis(); System.out.printf("(end - begin)*1.0/cycle:%.6f ",(end - begin)*1.0/cycle); } }

    比较结果:

    从结果可以看出:方式1明显快于方式2!

    包装类型Interger数组转ArrayList!

    Arrays.asList()!

  • 相关阅读:
    java_29打印流
    java_26 缓冲流
    java-27 Properties类的使用
    java_24.1文件流的应用--复制文件
    java_25 FileReader类和FileWriter类
    java_25.1字节转为字符OutputStreamWriter
    java_23 File类
    java_24 FileOutputStream类和FileInputStream类
    java_21 Set接口、HashSet类、LinkedSet类
    随机数Random和静态函数Math
  • 原文地址:https://www.cnblogs.com/iuyy/p/13501137.html
Copyright © 2020-2023  润新知