开发者

What is purpose of using asList?

开发者 https://www.devze.com 2023-03-25 10:47 出处:网络
I\'m just wondering what is the benefit and the purpose of the method asList() in Arrays. It returns a fixed-size list backed by the specified array, thus we cannot add elements to that list and it w

I'm just wondering what is the benefit and the purpose of the method asList() in Arrays.

It returns a fixed-size list backed by the specified array, thus we cannot add elements to that list and it will be just like an array (we can't add elements to it). Is there a way to convert a fixed-size list to a not-fixed-size list?

When I try to add elements to fixed-size list it throws UnsupportedOperationException:

Double[] d = {3.0开发者_如何学编程, 4.0, 5.0};
List<Double> myList = Arrays.asList(d);
myList.add(6.0); // here it will throw an exception


From java docs:

"This method acts as bridge between array-based and collection-based APIs"

For your question;

Double[] d = {3.0, 4.0, 5.0};
List<Double> yourList = new ArrayList(Arrays.asList(d));
yourList.add(6.0);


For use in other methods that require a List (or some super-interface of List, such as Collection or Iterable) as an argument. i.e.,

Double[] doubles = { 0d, 1d, 2d };
//... somewhere ...
someMethodThatRequiresAList(Arrays.asList(doubles));
//... elsewhere that you can't change the signature of ...
public void someMethodThatRequiresAList(List<Double> ds) { /* ... */ };


You can't convert it into a variable size list, but you can create a new one:

List<Double> myOtherList = new ArrayList<Double>(myList);
myOtherList.add(6.0);

Also, note that myList is a view over the array. So if you change the array

   d[0] = 0.0;
   System.out.println(myList);

you will get [0.0, 4.0, 5.0]

In many, many cases a fixed size list will do just fine, but of course it depends on what you are doing. I personally tend to use Arrays.asList a lot in test cases.


Just some comments, the java doc says it all:

public static <T> List<T> asList(T... a)

Returns a fixed-size list backed by the specified array.

Underneath, asList returns an Array.ArrayList instance, which is different from java.util.ArrayList. The only method allow you to modify the list is:

public E set(int index, E element) {...}


From the javadocs:

This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray().

So, if you want to be able to pass an array to a method expecting a Collection this provides a convenient way to do it.


It's used to create a view of the array as a List, so you can pass it to many methods that accept a List/Collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消