[Logo]
Forums Register Login
Collections :List.add throws runtime Exception(Unsupported Exceptions)
please see the code given below



i am getting the following Exception during runtime

element 0::test0
element 1::test1
element 2::test2
element 3::test3
element 4::test4
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:91)
at ListTest.main(ListTest.java:24)

After seeing all the javadocs , what i understood is Arrays.asList returns a fixedsize list backed by array .

is this Exception has anything to do with this Fixed Size?

what i am thinking is as it returns a fixed size list we are not allowed to add new elements to it ,please tell me whether i am correct or not .If this is the case , wouldn't it throw some other exception?

sorry if this is a silly question.

Thanks in advance

Hey Suresh,

It seems like a reasonable exception to me, are you thinking there is a more suitable one?
It's fixed size list, you can replace(update) with new elements rather than add new elements.
You cannot perform <Collection>.add or <Collection>.addAll operation on collections you have obtained from Arrays.asList .. only remove operation is permitted ..

Same applies for the collections obtained via Map.values() operation..

Thanks
Sajith
Hi all,

What i think is, Array has fixed-size. and when we retrieve list from array using Arrays.asList(...), it returns the arrays element in list format and, both array and list points to the same object.
If we try to add new element in list, it means we try to add element in array also which is fixed-size. so it get exception.

please, correct me if i am wrong..

Thanks,
Ankit
 
Ankit Gareta wrote:
What i think is, Array has fixed-size. and when we retrieve list from array using Arrays.asList(...), it returns the arrays element in list format and, both array and list points to the same object.


Not literally, but yes you are correct. The new list object will act as "bridge" and propagate any changes made (to the list) to the array object.

FWIW, Java 7 is intelligent to use the SAME list object how many ever times the Arrays.asList() is called using the same array object.

- Rakesh
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Dec 17, 2017 05:12:47.