Arrays.asList()如何在Java项目中使用

本篇文章给大家分享的是有关Arrays.asList()如何在Java项目中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

我们提供的服务有:成都网站制作、网站建设、外贸网站建设、微信公众号开发、网站优化、网站认证、义县ssl等。为成百上千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的义县网站制作公司

Arrays.asList() 是将数组作为列表。

问题来源于:

public class Test {
 public static void main(String[] args) {
  int[] a = {1, 2, 3, 4};
  List list = Arrays.asList(a);
  System.out.println(list.size()); //1
 }
}

期望的输出是 list 里面也有4个元素,也就是 size 为4,然而结果是1。

原因如下:

在 Arrays.asList 中,该方法接受一个变长参数,一般可看做数组参数,但是因为 int[] 本身就是一个类型,所以 a 变量作为参数传递时,编译器认为只传了一个变量,这个变量的类型是 int 数组,所以 size 为 1,相当于是 List 中数组的个数。基本类型是不能作为泛型的参数,按道理应该使用包装类型,但这里缺没有报错,因为数组是可以泛型化的,所以转换后在 list 中就有一个类型为 int 的数组。

/**
 * 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}.
 *
 * <p>This method also provides a convenient way to create a fixed-size
 * list initialized to contain several elements:
 * <pre>
 *   List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
 * </pre>
 *
 * @param a the array by which the list will be backed
 * @return a list view of the specified array
 */
@SafeVarargs
public static <T> List<T> asList(T... a) {
 return new ArrayList<>(a);
}

返回一个受指定数组支持的固定大小的列表。(对返回列表的更改会“直写”到数组。)此方法同 Collection.toArray 一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的。

所以,如果是创建多个列表,在传参数时候,最好使用 Arrays.copyOf(a) 方法,不然,对列表的更改就相当于对数组的更改。

public class Test {
 public static void main(String[] args) {
  Integer[] a = {1, 2, 3, 4};
  List list = Arrays.asList(a);
  System.out.println(list.size()); //4
 }
}

最后提醒,如果 Integer[] 数组没有赋值的话,默认是 null,而不是像 int[] 数组默认是 0。

以上就是Arrays.asList()如何在Java项目中使用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。

新闻标题:Arrays.asList()如何在Java项目中使用
标题URL:https://www.cdcxhl.com/article38/pgjssp.html

成都网站建设公司_创新互联,为您提供企业网站制作网站制作定制开发面包屑导航自适应网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设