简易做法

1
2
String id = "a,b,c";
List<String> ids = Arrays.asList(id.split(","));

在使用前,可以先尝试看一下 Arrays.asList() 的源码,这有助于防范一些比较明显的错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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 <T> the class of the objects in the array
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}

在这个方法中,文档一开始就告诉我们,这个方法返回的是一个定长的数列。所以当我们添加或删除当中的元素时是会抛出异常的,所以我们需要将它进行转化一下
当然,如果并不需要添加或删除当中的元素,是可以不用转化的。

转化

这里使用构造函数直接构造一个相同内容、不定长度的 ArraysList
构造函数如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}

文档中提到,该构造函数用于生成包含指定元素的 ArraysList ,也就是说并没有长度限制。

1
2
3
String id = "a,b,c";
List<String> ids = Arrays.asList(id.split(","));
List<String> ids2 = new ArraysList<>(ids);

简化一下就是

1
2
String id = "a,b,c";
List<String> ids = new ArraysList<>(Arrays.asList(id.split(",")));

这样子就完成了一个数组转不定 List 的方法。