简体   繁体   English

Arrays.asList()方法是否支持char[]数组?

[英]Is it Arrays.asList ( ) method support the char[ ] array?

We can use Arrays.asList( ) method for String[ ] and Integer[ ] arrays. Can we use the char[ ] array in Arrays.asList( ) method?我们可以使用 Arrays.asList( ) 方法来获取 String[ ] 和 Integer[ ] arrays。我们可以在 Arrays.asList( ) 方法中使用 char[ ] 数组吗?

Arrays.asList(75,85,95,70);
Arrays.asList("String", "Integer", "Character");

Your question is conflating arrays with varargs arguments.您的问题是将 arrays 与可变参数 arguments 混为一谈。

In your example:在你的例子中:

Arrays.asList(75,85,95,70);

the 75,85,95,70 is not an Integer[] or an int[] . 75,85,95,70不是Integer[]int[] It is actually a sequence of int values for a varargs parameter.它实际上是可变参数参数的一系列int值。

What actually happens is that the int values are autoboxed to Integer values and these are then assembled into an Integer[] .实际发生的是int值被自动装箱为Integer值,然后将它们组装成Integer[] (The autoboxing and array construction happens at the call site!) (自动装箱和数组构造发生在调用站点!)

The Integer[] is then passed to asList method with Integer as the inferred type parameter T .然后将Integer[]传递给asList方法, Integer作为推断类型参数T


So to answer question that you asked:所以回答你问的问题:

Is it Arrays.asList() method support the char[] array? Arrays.asList()方法是否支持char[]数组?

Yes and no.是和不是。

On the one hand:一方面:

  List<Character> charList = Arrays.asList('a', 'b', 'c');

will compile and give you a list of characters in the same way that your int example does.将以与您的int示例相同的方式编译并为您提供字符列表。 Note that the result is a List<Character> rather than a List<char> .请注意,结果是List<Character>而不是List<char>

One the other hand:另一方面:

  char[] test = char[]{'a', 'b', 'c'};
  Arrays.asList(test);

will produced a List<char[]> with a single list element.将生成一个带有单个列表元素的List<char[]> Indeed, if you have an actual char[] (as distinct from a sequence of char parameters), then asList cannot convert that to List<Character> .事实上,如果您有一个实际的char[] (与一系列char参数不同),则asList无法将其转换为List<Character>

The Java char keyword is a primitive data type. Java char 关键字是原始数据类型。 So that's why we can't simply convert it.所以这就是为什么我们不能简单地转换它。

You can do it as below First convert char array to string then map it's chars to list您可以按如下方式进行 首先将 char 数组转换为字符串,然后将 map 转换为要列出的字符

import java.util.stream.Collectors;
import java.util.List;
char[] chars = {'c','d','e', 'f','g'};
        List<Character> cahrList = String.valueOf(chars).chars().mapToObj(c -> (char) c).collect(Collectors.toList());

You can use the Character class for char primitive data type:您可以将Character class 用于 char 原始数据类型:

import java.util.Arrays;
import java.util.List;

public class TestCode {
    public static void main(String[] args) {
        List<Character> charList = Arrays.asList('c','d','e', 'f','g');
        System.out.println(charList);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM