Forums Register Login

Collections :List.add throws runtime Exception(Unsupported Exceptions)

+Pie Number of slices to send: Send
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

+Pie Number of slices to send: Send
Hey Suresh,

It seems like a reasonable exception to me, are you thinking there is a more suitable one?
+Pie Number of slices to send: Send
It's fixed size list, you can replace(update) with new elements rather than add new elements.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
 

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
Come have lunch with me Arthur. Adventure will follow. This tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 4787 times.
Similar Threads
Using asList with Generics
List Iterator error - please explain
Split String by $
Arrays.toArray : All my knowledge collapses ...
Collections - Arrays.asList() / List.add()
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 13:51:15.