Abhishek Saxena
Abhishek Saxena

Reputation: 292

Why Runtime exception on calling add for a fixed size list?

Below is my list defination.

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

The list is having fixed size as 5.

On calling a add like this

list.add(200);

Should not this be a compile time error ? Rather it threw below exception at runtime

java.lang.UnsupportedOperationException

Upvotes: 4

Views: 227

Answers (3)

Jabir
Jabir

Reputation: 2866

From Java DOCs

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 fixed size so you cant modify add elements to this list.

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

We knew that Arrays.asList returns a List of fixed size backed by an array of fixed length.

Now the compiler doesn't know the length of the array at compile time. unless you run the program, you don't know the length at runtime.

In short, you can't modify an array at compile time :)

Upvotes: 4

Shriram
Shriram

Reputation: 4411

This List implementation you receive from Arrays.asList is a special view on the array - you can't change it's size.

Upvotes: 2

Related Questions