Arrays.asList(int[]) 不起作用 [英] Arrays.asList(int[]) not working

查看:27
本文介绍了Arrays.asList(int[]) 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下代码时,没有打印输出.

When I run the following code, no output is printed.

int[] array = {3, 2, 5, 4};

if (Arrays.asList(array).contains(3))
{
    System.out.println("The array contains 3");
}

推荐答案

当您将原始数组(在您的情况下为 int[])传递给 Arrays.asList 时,它创建一个 List 与单个元素 - 数组本身.因此 contains(3) 返回 false.contains(array) 将返回 true.

When you pass an array of primitives (int[] in your case) to Arrays.asList, it creates a List<int[]> with a single element - the array itself. Therefore contains(3) returns false. contains(array) would return true.

如果你使用 Integer[] 而不是 int[],它会起作用.

If you'll use Integer[] instead of int[], it will work.

Integer[] array = {3, 2, 5, 4};

if (Arrays.asList(array).contains(3))
{
  System.out.println("The array contains 3");
}

进一步解释:

asList 的签名是 List;asList(T...).原语不能替换泛型类型参数.因此,当您向该方法传递一个 int[] 时,整个 int[] 数组将替换 T 并得到一个 List<int[]>.另一方面,当您将 Integer[] 传递给该方法时,Integer 替换 T 并且您得到一个 List;.

The signature of asList is List<T> asList(T...). A primitive can't replace a generic type parameter. Therefore, when you pass to this method an int[], the entire int[] array replaces T and you get a List<int[]>. On the other hand, when you pass an Integer[] to that method, Integer replaces T and you get a List<Integer>.

这篇关于Arrays.asList(int[]) 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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