Why is a runtime exception when add is called for a fixed-size list?

The following is a limitation of my list.

static List<Integer> list = Arrays.asList(112, 323, 368, 369, 378); 

The list has a fixed size of 5.

When calling add like this

 list.add(200); 

Isn't that a compile-time error? Rather, he threw below runtime exceptions

 java.lang.UnsupportedOperationException 
+4
source share
3 answers

We knew that Arrays.asList returns a List fixed size, supported by a fixed-length array .

Now the compiler does not know the length of the array at compile time. if you do not run the program, you do not know its length at run time.

In short, you cannot change the array at compile time :)

+4
source

From Java DOC

 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 Collection.toArray(). The returned list is serializable and implements RandomAccess. This method also provides a convenient way to create a fixed-size list initialized to contain several elements: List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); Parameters: a - the array by which the list will be backed Returns: a list view of the specified array 

Since this is a fixed size, therefore, you cannot change the items added to this list.

+3
source

This implementation of the list that you get from Arrays.asList is a special kind of array - you cannot resize it.

+2
source

All Articles