Tag Archives: java.lang.UnsupportedOperationException

[Solved] Arrays.asList() Error: java.lang.UnsupportedOperationException

1. Report an error

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(AbstractList.java:148)
	at java.util.AbstractList.add(AbstractList.java:108)
	at 

2. Reason

Before packaging items do when a utility class for converting between strings and arrays, abnormal is present in Arrays.asList()the.

public static List stringToList(String str, String separator) {
    List r = new ArrayList<>();
    if (BayouUtil.isNotEmpty(str)) {
        if (str.contains(separator)) {
            r = Arrays.asList(str.split(separator));	
        } else {
            r.add(str);
        }
    }
 
    return r;
}

Use asListis returned Arrayswithin the classArrayList

@SafeVarargs
@SuppressWarnings("varargs")
public static  List asList(T... a) {
    return new ArrayList<>(a);
}
 
private static class ArrayList extends AbstractList
    implements RandomAccess, java.io.Serializable
{
    private static final long serialVersionUID = -2764017481108945198L;
    private final E[] a;
 
    ArrayList(E[] array) {
        a = Objects.requireNonNull(array);
    }
......
}

And its successor, the AbstractListparent class add()remove()and clear() methods underlying the final will throw an exception.

public void add(int index, E element) {
    throw new UnsupportedOperationException();
}
 
public E remove(int index) {
    throw new UnsupportedOperationException();
}
 
private void rangeCheckForAdd(int index) {
    if (index < 0 || index > size())
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

ListIn the interface add()remove()andclear()

image-20210810175025705

image-20210810175056375

Therefore, the use asListof add() remove() clear()other methods will ultimately throw UnsupportedOperationExceptionan exception.

And why ArrayList()Why does not complain? Because ArrayListthe rewrite add removeand clear methods

public void add(E e) {
    checkForComodification();
 
    try {
        int i = cursor;
        ArrayList.this.add(i, e);
        cursor = i + 1;
        lastRet = -1;
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}
 
public void remove() {
    if (lastRet < 0)
        throw new IllegalStateException();
    checkForComodification();
 
    try {
        ArrayList.this.remove(lastRet);
        cursor = lastRet;
        lastRet = -1;
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}
 
public Object clone() {
    try {
        ArrayList<?> v = (ArrayList<?>) super.clone();
        v.elementData = Arrays.copyOf(elementData, size);
        v.modCount = 0;
        return v;
    } catch (CloneNotSupportedException e) {
        // this shouldn't happen, since we are Cloneable
        throw new InternalError(e);
    }
}

3. Solution

r = new ArrayList<>(Arrays.asList(str.split(separator)));
// or
r.addAll(Arrays.asList(str.split(separator)));

Note: Arrays.asList() is a big pit, use it with caution

How to Solve Mybatis Error: java.lang.UnsupportedOperationException

The error information is as follows:

Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.UnsupportedOperationException

Exception root: resulttype returns the element type in the collection, not the collection itself

The code is as follows:

    <!--Check detailed order information-->
    <resultMap id="orderDetailMap" type="com.alibaba.fastjson.JSONArray">
        <result column="order_code" property="orderCode"/>
        <result column="state" property="state"/>
        <result column="address" property="address"/>
        <result column="received_telephone" property="receivedTelephone"/>
        <result column="send_linkman" property="sendLinkman"/>
        <result column="send_telephone" property="sendTelephone"/>
        <result column="delivery_time" property="deliveryTime"/>
        <result column="delivery_time_quantum" property="deliveryTimeQuantum"/>
        <result column="greeting_card" property="greetingCard"/>
        <result column="show_pay_name" property="showPayName"/>
        <result column="pay_time" property="payTime"/>
        <result column="order_total_amount" property="orderTotalAmount"/>
        <result column="is_invoice" property="isInvoice"/>
        <result column="settled_amount" property="settledAmount"/>
        <result column="delivery_money" property="deliveryMoney"/>
        <collection property="goods" column="order_code"  ofType="com.alibaba.fastjson.JSONObject" javaType="List" select="findOrderChildDetail">
            <result column="item_sku_code" property="itemSkuCode"/>
            <result column="sku_title" property="skuTitle"/>
            <result column="sale_price" property="salePrice"/>
            <result column="buy_cnt" property="buyCnt"/>
            <result column="totalPrice" property="totalPrice"/>
        </collection>
    </resultMap>
    <select id="queryOrderDetail" parameterType="Map" resultMap="orderDetailMap">
        SELECT
            order_code,
            state,
            received_linkman,
            CONCAT(received_address_area,received_address_desc) AS 'address',
            received_telephone,
            send_linkman,
            send_telephone,
            delivery_time,
            delivery_time_quantum,
            greeting_card,
            show_pay_name,
            pay_time,
            order_total_amount,
            is_invoice,
            settled_amount,
            delivery_money
        FROM
            order_info
        WHERE
            account_code = #{accountCode}
        AND
            order_code = #{orderCode}
        LIMIT 1
    </select>

    <!--Check detailed order information-->
    <select id="findOrderChildDetail" parameterType="String" resultType="com.alibaba.fastjson.JSONObject">
        SELECT
            item_sku_code ,
            sku_title ,
            sale_price ,
            buy_cnt ,
            sale_price *  buy_cnt AS totalPrice
        FROM
            order_detail
        WHERE
            order_code = #{orderCode}
    </select>
    

Error reason:

    <resultMap id="orderDetailMap" type="com.alibaba.fastjson.JSONArray">
    The JSONArray type in the error, modified to
    <resultMap id="orderDetailMap" type="com.alibaba.fastjson.JSONObject">

Note: the type here is the type used in the current development. If the object is used, check whether the type in the resultmap is a list or an object. If it is an associated subquery, modify it to an object