Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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
like image 496
Abhishek Saxena Avatar asked Jan 07 '23 20:01

Abhishek Saxena


1 Answers

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 :)

like image 60
Suresh Atta Avatar answered Feb 03 '23 16:02

Suresh Atta