首页 > 其他分享 >数组 => list

数组 => list

时间:2022-10-23 20:57:34浏览次数:49  
标签:code 数组 Arrays list strArrays strList array asList

  • Arrays.asList(T....a)
  • new ArrayList<>(Arrays.asList());
  • Collections.addAll() ***
  • Stream流

Arrays.asList(T....a)

String[] strArrays = new String[]{"This","is","a","Arrays"};
System.out.println("strArrays: "+Arrays.toString( strArrays));

List<String> strList = Arrays.asList(strArrays);  // Arrays.asList() 返回值就是一个 list
System.out.println("strList: "+ strList);

输出:
    strArrays: [This, is, a, Arrays]
	strList: [This, is, a, Arrays]

注意

在查看源码后可发现:

//Arrays.java

	  private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;   // 注意这里,private final  私有内部类,

        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }
      ....    
	}

      
  	@SafeVarargs
    @SuppressWarnings("varargs")
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

发现:

  1. 返回值 a 被pricate final修饰
  2. a直接指向array数组所在位置

思考:

Arrays.asList() 的返回值a被private final进行修饰,意味着什么:

  1. private:外部无法获取a,即无法对属性进行修改
  2. final:a的地址不可变。
    1. a会是一个指向堆区的对象数组(泛型)。指向的地址不可变,即意味着该数组尺寸固定,不可进行扩容。

意义:

  1. 方法返回的 list 不支持,remove(),add()等修改列表长度的操作
  2. 方法返回的仅仅只是一个视图,无论是array本身的变化,还是list进行的修改,都会对彼此的产生影响。
  3. 作为方法的参数,T....a 是个泛型。因此不支持基本数据操作。
验证2
 //
        strArrays[1] = "not";
        strList.set(2,"realArray") ;

        System.out.println("After changing:");
        System.out.println("strArrays: "+Arrays.toString( strArrays));
        System.out.println("strList: "+ strList);

new ArrayList<>(Arrays.asList());

String[] strArrays = new String[]{"This","is","a","static","Arrays"};
System.out.println("strArrays: "+Arrays.toString( strArrays));

List<String> strList = new ArrayList<>(Arrays.asList(strArrays));
System.out.println("strList: "+ strList);

直接调用了 ArrayList() 的构造方法,创建了一个新的 list ,与第一种方法相比较,可以进行任意的扩容,

strList.add(3,"not");
System.out.println("strArrays: "+Arrays.toString( strArrays));
System.out.println("strList: "+ strList);

刚开始好奇,为什么入参还需要使用 Arrays.asList() 方法。看了一下发现,ArrayList 的构造方法,不支持数组类型的参数

Collections.addAll()

String[] strArrays = new String[]{"This","is","a","static","Arrays"};

List<String> strList = new ArrayList<>(strArrays.length);
Collections.addAll(strList, strArrays);
System.out.println("strList: " + strList);
  • Collections.addAll()源码注释

    Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

这种方法要比其他任何方法都要有更快的速度,是最为高效的。代码上没看出什么意思,查了一下貌似是:将数组中的元素转为二进制,然后添加入List中,enmmm,既然都二进制了,快就快把

目前java8 仅支持int、long、double类型的数组

List<Integer> intList= Arrays.stream(new int[] { 1, 2, 3, }).boxed().collect(Collectors.toList());
List<Long> longList= Arrays.stream(new long[] { 1, 2, 3 }).boxed().collect(Collectors.toList());
List<Double> doubleList= Arrays.stream(new double[] { 1, 2, 3 }).boxed().collect(Collectors.toList());

不大懂流,还没怎么么学。

    /**
     * 创建一个长度适合的流?
     * Returns a sequential {@link IntStream} with the specified array as its
     * source.
     * 
     * @param array the array, assumed to be unmodified during use
     * @return an {@code IntStream} for the array
     * @since 1.8
     */
    public static IntStream stream(int[] array) {
        return stream(array, 0, array.length);
    }
/**
 * 将基本数据类型转化为包装类
 * Returns a {@code Stream} consisting of the elements of this stream,
 * each boxed to an {@code Integer}.
 *
 * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 * operation</a>.
 *
 * @return a {@code Stream} consistent of the elements of this stream,
 * each boxed to an {@code Integer}
 */
Stream<Integer> boxed();
    /**
     * Performs a <a href="package-summary.html#MutableReduction">mutable
     * reduction</a> operation on the elements of this stream using a
     * {@code Collector}.  A {@code Collector}
     * encapsulates the functions used as arguments to
     * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of
     * collection strategies and composition of collect operations such as
     * multiple-level grouping or partitioning.
     *
     * <p>If the stream is parallel, and the {@code Collector}
     * is {@link Collector.Characteristics#CONCURRENT concurrent}, and
     * either the stream is unordered or the collector is
     * {@link Collector.Characteristics#UNORDERED unordered},
     * then a concurrent reduction will be performed (see {@link Collector} for
     * details on concurrent reduction.)
     *
     * <p>This is a <a href="package-summary.html#StreamOps">terminal
     * operation</a>.
     *
     * <p>When executed in parallel, multiple intermediate results may be
     * instantiated, populated, and merged so as to maintain isolation of
     * mutable data structures.  Therefore, even when executed in parallel
     * with non-thread-safe data structures (such as {@code ArrayList}), no
     * additional synchronization is needed for a parallel reduction.
     *
     * @apiNote
     * The following will accumulate strings into an ArrayList:
     * <pre>{@code
     *     List<String> asList = stringStream.collect(Collectors.toList());
     * }</pre>
     *
     * <p>The following will classify {@code Person} objects by city:
     * <pre>{@code
     *     Map<String, List<Person>> peopleByCity
     *         = personStream.collect(Collectors.groupingBy(Person::getCity));
     * }</pre>
     *
     * <p>The following will classify {@code Person} objects by state and city,
     * cascading two {@code Collector}s together:
     * <pre>{@code
     *     Map<String, Map<String, List<Person>>> peopleByStateAndCity
     *         = personStream.collect(Collectors.groupingBy(Person::getState,
     *                                                      Collectors.groupingBy(Person::getCity)));
     * }</pre>
     *
     * @param <R> the type of the result
     * @param <A> the intermediate accumulation type of the {@code Collector}
     * @param collector the {@code Collector} describing the reduction
     * @return the result of the reduction
     * @see #collect(Supplier, BiConsumer, BiConsumer)
     * @see Collectors
     */
没看懂,大体意思应该是将流转化为 list 进行返回吧
    <R, A> R collect(Collector<? super T, A, R> collector);

标签:code,数组,Arrays,list,strArrays,strList,array,asList
From: https://www.cnblogs.com/serendipity-igao/p/16819490.html

相关文章

  • cat userlist
    Linux文件系统的三层抽象是什么?写出Catuserlist的过程,要详述目录文件,i-node.数据块,要画图示意假设块大小为4k,userlist的大小不小于10k,自己假设大小一、Linux文件......
  • LinkedList集合
    (1)底层数据结构是双链表,查询慢,增删快,但是如果操作的是首尾元素,速度也是极快的。(2)LinkedList本身多了很多直接操作首尾元素的特有API。(其实实际上很少用,基本上用Collection......
  • cat userlist
    Linux文件系统的三层抽象是什么?第一层抽象:一个磁盘能够储存大量的数据,一个磁盘可以被划分成分区,每个分区可以看作是一个独立的磁盘。第二层抽象:一个硬盘有一些磁性盘片......
  • ArrayList集合底层原理
    (1)利用空参创建的集合,在底层创建一个默认长度为0的数组;(2)添加第1个元素时,底层创建一个新的长度为10的数组;(3)存满时,会扩容1.5倍;(4)如果一次添加多个数据,1.5倍还放不下,则新创建......
  • 累加和为 K 的子数组问题
    累加和为K的子数组问题作者:Grey原文地址:博客园:累加和为K的子数组问题CSDN:累加和为K的子数组问题题目说明数组全为正数,且每个数各不相同,求累加和为K的子数组组......
  • cat userlist
    catuserlist三层抽象第一层抽象磁盘会被分成一个一个的扇形区域,每个扇形区域有着相同的属性,相互独立。第二层抽象磁盘的每个相对独立的扇形区域都是由块数组构成......
  • List和Map、Set的区别
    List和Map、Set的区别结构特点List和Set是存储单列数据的集合,Map是存储键和值这样的双列数据的集合;List中存储的数据是有顺序,并且允许重复;Map中存储的数据是没有顺序的,......
  • ① 定义一个大小为10 的整形数组a; ② 从键盘输入10 个整数,放置到数组a 中; ③ 输出数组
    publicstaticvoidmain(String[]args){ Scannerinput=newScanner(System.in); int[]a=newint[10];//定义一个数组 //给数组的10个元素赋值 for(inti=0;i......
  • kafka listeners和advertised.listeners配置
    一、概述#Theaddressthesocketserverlistenson.Itwillgetthevaluereturnedfrom#java.net.InetAddress.getCanonicalHostName()ifnotconfigured.#FORMA......
  • #yyds干货盘点# 动态规划专题:连续子数组最大和
    1.简述:描述给定一个长度为 的数组,数组中的数为整数。请你选择一个非空连续子数组,使该子数组所有数之和尽可能大,子数组最小长度为1。求这个最大值。输入描述:第一行为一个正......