The analysis and solution of Unsupportedoperationexception

Source: Internet
Author: User

The analysis and solution of Unsupportedoperationexception

You may encounter an exception like this when you are manipulating the list object.
Java.lang.UnsupportedOperationException
At Java.util.AbstractList.remove (Unknown Source)
At Java.util.abstractlist$itr.remove (Unknown Source)
At Java.util.AbstractCollection.remove (Unknown Source)

In a later look at the problem, I suddenly thought of a previous piece of code appears to be a problem.
That's a way.
Public list<xxxx> getxxxx () {
Return Arrays.aslist (Objectarray);
}

Where the Objectarray is an array of objects, the return is object[]. For convenience, the occasional machine

I used the Arrays.aslist () method. The result has no compilation exception. When I was running,

Throws an exception that cannot be converted. The object is roughly converted to a XXXX object conversion exception.

In fact, from the exception information can be seen that the root of the problem is that the Arrays.aslist () method returns a

Abstractlist objects, not ArrayList objects.

The anomaly has been found at all. Then let's talk about how to solve this anomaly.
My approach is to define a temporary list object in the method body, with ArrayList.
List L = new ArrayList ();
Of course, it can be paradigm-oriented.
list<xxxx> L = new arraylist<xxxx> ();

Then, add a for loop to the L list and finally return to the list.

Complete code:

Public list<xxxx> getxxxx () {
list<sysrole> list = new arraylist<sysrole> ();

for (Object O:objectarray) {
Sysrole user = (Sysrole) o;

List.add (user);
}

return list;
}

This solves the anomaly.

There is also a link in English, we can see.

http://www.theserverside.com/discussions/thread.tss?thread_id=38493

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.