Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of using Arrays.asList() to initialize a List [duplicate]

Tags:

I use this below code. Both are working fine in my application.

Case 1.

List<String> coreModules =     new ArrayList<String>(Arrays.asList(         "TOOLBAR_TO_DO_LIST",         "TOOLBAR_PROPERTY",         "TOOLBAR_PEOPLE",         "TOOLBAR_INSURANCE",         "TOOLBAR_BATCH",         "TOOLBAR_INFORMATION_REFERENCE",         "TOOLBAR_LR_PROPERTY",         "TOOLBAR_CASE_FOLDER",         "TOOLBAR_INSPECTION_RESULT",         "TOOLBAR_MY_OFFICE")); 

Case 2.

List<String> coreModules =     Arrays.asList(         "TOOLBAR_TO_DO_LIST",         "TOOLBAR_PROPERTY",         "TOOLBAR_PEOPLE",         "TOOLBAR_INSURANCE",         "TOOLBAR_BATCH",         "TOOLBAR_INFORMATION_REFERENCE",         "TOOLBAR_LR_PROPERTY",         "TOOLBAR_CASE_FOLDER",         "TOOLBAR_INSPECTION_RESULT",         "TOOLBAR_MY_OFFICE"); 

But I have some questions:

  1. Which one is better one performance-wise?
  2. In which case prefer Case 2?
like image 503
Sitansu Avatar asked Dec 12 '13 08:12

Sitansu


People also ask

What does Arrays asList () do?

The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.

Does Arrays asList make a copy?

The method only creates a List wrapper upon the underlying array. Because of which, both the array and the newly created list continue to refer to the exact same elements. That is why, no elements are copied when we use asList method.

How is Arrays asList () different than the standard way of initializing list?

How is Arrays. asList() different than the standard way of initialising List? Explanation: List returned by Arrays. asList() is a fixed length list which doesn't allow us to add or remove element from it.


1 Answers

Case 2 is better performance-wise BUT: it returns a List with an immutable size. Meaning you cannot add/remove elements to/from it:

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

Arrays#asList

like image 191
Lital Kolog Avatar answered Oct 02 '22 23:10

Lital Kolog