UnsupportedOperationException while removing or adding elements to a List

+1 vote
asked Feb 27, 2017 by Hitesh Garg (352 points)  

I have created a list from Arrays.asList and while manipulating that list I am getting UnsupportedOperationException, both at list.add() and list.remove() methods.
What is the problem with the code and how to fix this?

final Long[] arr = {1.0L, 2.0L};
List myNewList = Arrays.asList(someArrayOfLong);

myNewList.add(new Long(3)); //add an element in the list.
myNewList.remove(0); //remove element from the list at index 0.

1 Answer

+1 vote
answered Feb 27, 2017 by Rahul Singh (543 points)  

This happens because Arrays.asList returns an immutable list, which is non modifiable and according to official documentation -

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.

For more details look at this detailed post on how to convert an array to a List

124 questions

41 answers


928 users

Most popular tags

java python python3 oracle database java-8 sql-server python2 oracle11g git oracle-12g command-line maven sql-server-2012 sql input array list fenitoina dilantin java的 angular javascripts git-branch intellij-idea hashmap collection file-io io temovate clobetasol ampicillin principen daclatasvir daklinza vasotec enalapril nexium esomeprazole tadalafil tadlis sildenafil citrate pefomax xeloda capecitabina clobetasol temovate stemetil prochlorperazine methotrexate methotrexate sildenafilo y dapoxetina super kamagra norvasc amlodipine citalopram celexa amitriptylin saroten vitamin b12 methylcobalamin valaciclovir valtrex zudena udenafil sildenafil citrate vigour depakote divalproex retin-a tretinoine sildenafil citrate ip-max nizoral ketoconazol ciaton tadalafil norethisteronacetat aygestin indomethacin indocin tiova tiotropium bromid finasterida proscar lithium carbonate eskalith finasterida propecia levitra vardenafil vantin cefpodoxima loxitane loxapine rulide roxithromycine avodart dutasterid tecnomax sildenafil citrate methylcobalamin vitamin b12 permethrin acticin etinilestradiol norgestrel ovral pk-merz amantadin cycrin medroxyprogesterone serophene clomiphene spironolactone aldactone mesalazin pentasa zebeta bisoprolol cytodrox hydroxyurea ampicillin ampicillin pletal cilostazol paracetamol panadol pepcid famotidina meclizine hydrochloride antivert donaton tadalafil sdf dsfs sdgfgsdg mac null-pointer-exception constructor oracle-12c terminal hibernate-5 hibernate git-merge es6 programming git-amend git-commit java-stream git-remote multithreading access-modifiers nested-classes
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.