使用Arrays.asList将基元数组转换为List [英] Converting an array of primitives to List using Arrays.asList

查看:125
本文介绍了使用Arrays.asList将基元数组转换为List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

import java.util.Arrays;
import java.util.ArrayList;
public class Test1 {

    public static void main(String[] args) {

      double[] a = new double[2];

      for( double d : Arrays.asList(a)) 
            System.out.println(d); 
  }

}

输出:

$ javac Test1.java 
Test1.java:9: error: incompatible types
      for( double d : Arrays.asList(a)) 
                                   ^
  required: double
  found:    double[]
1 error

为什么我在这里收到错误?

Why am I getting an error here?

错误是什么意思?是什么告诉我的?

推荐答案

你在这里遇到错误,因为当你使用这个功能时接受varargs,这个函数在场景后面创建一个新的对象数组。所以, Arrays.asList(1,2,3)实际上是一个整数数组

传入一个整数数组, Arrays.asList()在场景后面创建一个整数数组。这就是为什么你不能用以下循环迭代它:

You're getting an error here because when you work with the function which accepts varargs, this functions creates behind a scene a new array of objects you passed in it. So, Arrays.asList(1,2,3) gets, in fact, an array of integers.
When you pass in an array of integers, Arrays.asList() creates an array of arrays of integers behind the scene. That's why you can't iterate over it with the following loop:

for( double d : Arrays.asList(a)) 

尝试改变它:

for(double[] d : Arrays.asList(a)) 

你会看到 d 实际上是对你传递给 Arrays.asList() - a

And you'll see that d is, in fact, reference to the array you passed into the Arrays.asList() - a.

这篇关于使用Arrays.asList将基元数组转换为List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆