java.lang.UnsupportedOperationException怎么解决?

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 在Java中,`Arrays.asList()`方法用于将数组转换为列表,但返回的是一个固定大小的列表,它继承自`AbstractList`,不支持`add()`, `remove()`, 或其他可变操作。当尝试对这样的列表执行这些操作时,会抛出`UnsupportedOperationException`。
1.  现象 java.lang.UnsupportedOperationException

php

代码解读

复制代码

Exception in thread "main" java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
Caused by: java.lang.UnsupportedOperationException
	at java.util.AbstractList.remove(AbstractList.java:161)
	at java.util.AbstractList$Itr.remove(AbstractList.java:374)
	at java.util.AbstractCollection.remove(AbstractCollection.java:293)
	at com.seeyon.apps.LoginTest.main(Test.java:17)
	... 5 more

2. 审查代码

java

代码解读

复制代码

import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) throws Exception {
        String str2 = "组通〔2021〕51号 ,组通〔2021〕51号 ,组通〔2021〕51号 ,组通〔2021〕51号 ";
        String str3 = "-3553969955535829665,-8291168891934981275,-5572834578246384948,-3366368013864383456";

        List<String> docNames= Arrays.asList(str2.split(","));
        List<String> docIds2 = Arrays.asList(str3.split(","));
        docNames.remove("组通〔2021〕51号 ");
        docIds2.remove("-8291168891934981275");
        System.out.println(docNames);
        System.out.println(docIds2);

    }
}
3.  查看Arrays.asList()  源码

java

代码解读

复制代码

    @SafeVarargs
    @SuppressWarnings("varargs")
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

    /**
     * @serial include
     */
    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;

        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }

        @Override
        public int size() {
            return a.length;
        }

        @Override
        public Object[] toArray() {
            return a.clone();
        }

        @Override
        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            int size = size();
            if (a.length < size)
                return Arrays.copyOf(this.a, size,
                                     (Class<? extends T[]>) a.getClass());
            System.arraycopy(this.a, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
        }

        @Override
        public E get(int index) {
            return a[index];
        }

        @Override
        public E set(int index, E element) {
            E oldValue = a[index];
            a[index] = element;
            return oldValue;
        }

        @Override
        public int indexOf(Object o) {
            E[] a = this.a;
            if (o == null) {
                for (int i = 0; i < a.length; i++)
                    if (a[i] == null)
                        return i;
            } else {
                for (int i = 0; i < a.length; i++)
                    if (o.equals(a[i]))
                        return i;
            }
            return -1;
        }

        @Override
        public boolean contains(Object o) {
            return indexOf(o) != -1;
        }

        @Override
        public Spliterator<E> spliterator() {
            return Spliterators.spliterator(a, Spliterator.ORDERED);
        }

        @Override
        public void forEach(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            for (E e : a) {
                action.accept(e);
            }
        }

        @Override
        public void replaceAll(UnaryOperator<E> operator) {
            Objects.requireNonNull(operator);
            E[] a = this.a;
            for (int i = 0; i < a.length; i++) {
                a[i] = operator.apply(a[i]);
            }
        }

        @Override
        public void sort(Comparator<? super E> c) {
            Arrays.sort(a, c);
        }
    }

此时发现Arrays.asList() 构造函数   是有其内部类 ArrayList 进行实例化的,而其内部类 ArrayList  并没有提供 remove() 方式,而是继承了 AbstractList 抽象类,顾Arrays.asList() 调用的是父类的remove() 方法;

java

代码解读

复制代码

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically
     * implicit.)
     */
    protected AbstractList() {
    }

    /**
     * Appends the specified element to the end of this list (optional
     * operation).
     *
     * <p>Lists that support this operation may place limitations on what
     * elements may be added to this list.  In particular, some
     * lists will refuse to add null elements, and others will impose
     * restrictions on the type of elements that may be added.  List
     * classes should clearly specify in their documentation any restrictions
     * on what elements may be added.
     *
     * <p>This implementation calls {@code add(size(), e)}.
     *
     * <p>Note that this implementation throws an
     * {@code UnsupportedOperationException} unless
     * {@link #add(int, Object) add(int, E)} is overridden.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     * @throws UnsupportedOperationException if the {@code add} operation
     *         is not supported by this list
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this list
     * @throws NullPointerException if the specified element is null and this
     *         list does not permit null elements
     * @throws IllegalArgumentException if some property of this element
     *         prevents it from being added to this list
     */
    public boolean add(E e) {
        add(size(), e);
        return true;
    }

    /**
     * {@inheritDoc}
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    abstract public E get(int index);

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }

   // 此处省略 很多源代码
   ''''
         
}



从 AbstractList 抽象类的源码中可以看到,在调用 set() ,add() , remove() 会抛出 throw new UnsupportedOperationException(); 自定义的异常。

4. 解决方法: 包一层 xxxList<>() 即可

java

代码解读

复制代码

 List<String> docNames= new ArrayList<>(Arrays.asList(str2.split(",")));
 List<String> docIds2 = new LinkedList<>(Arrays.asList(str3.split(",")));
 List<String> docIds2 = new CopyOnWriteArrayList<>(Arrays.asList(str3.split(",")));


相关文章
|
消息中间件 存储 canal
3分钟白话RocketMQ系列—— 如何保证消息不丢失
3分钟白话RocketMQ系列—— 如何保证消息不丢失
4942 1
|
Dubbo 大数据 应用服务中间件
【解决方法】Dubbo报错Data length too large
Data长度超过设置参数的最大值
|
Oracle Java 关系型数据库
如何判断jdk版本是32位还是64位?
如何判断jdk版本是32位还是64位?1、这个主要是在 cmd 下输入 java -version来查看,如果没有标明是多少位的,默认一般是32位的。2、看你在oracle官网下载的jdk文件原名:刚下载的JDK文件名后面标注了x64代表是64位的JDK,若没有标注,则都是32位的JDK(必须保证是官网下载的文件原名哦);当然此只是官网下载的文件,不包括手动更改的文件名。 比如: jdk-8u102-windows-i586是什么32位还是64位?没有标注x64,就说明是32位的。 64位后面都会带x64标识;不带就是32位的;
6787 0
如何判断jdk版本是32位还是64位?
|
2月前
|
存储 人工智能 运维
AI 网关代理 RAG 检索:Dify 轻松对接外部知识库的新实践
Higress AI 网关通过提供关键桥梁作用,支持 Dify 应用便捷对接业界成熟的 RAG 引擎。通过 AI 网关将 Dify 的高效编排能力与专业 RAG 引擎的检索效能结合,企业可在保留现有 Dify 应用资产的同时,有效规避其内置 RAG 的局限,显著提升知识驱动型 AI 应用的生产环境表现。
1779 89
|
缓存 NoSQL Java
阿里巴巴开源的通用缓存访问框架JetCache介绍
JetCache是由阿里巴巴开源的通用缓存访问框架,如果你对Spring Cache很熟悉的话,请一定花一点时间了解一下JetCache,它更好用。JetCache可以做类似Spring Cache的注解式缓存,支持TTL、多级缓存、分布式自动刷新,也提供类似JSR107规范的Cache API。
13244 1
|
Java 测试技术
【Java】已解决java.lang.UnsupportedOperationException异常
【Java】已解决java.lang.UnsupportedOperationException异常
2302 0
|
9月前
|
Cloud Native Java Nacos
springcloud/springboot集成NACOS 做注册和配置中心以及nacos源码分析
通过本文,我们详细介绍了如何在 Spring Cloud 和 Spring Boot 中集成 Nacos 进行服务注册和配置管理,并对 Nacos 的源码进行了初步分析。Nacos 作为一个强大的服务注册和配置管理平台,为微服务架构提供
3940 14
|
10月前
|
SQL 存储 大数据
Flink 基础详解:大数据处理的强大引擎
Apache Flink 是一个分布式流批一体化的开源平台,专为大规模数据处理设计。它支持实时流处理和批处理,具有高吞吐量、低延迟特性。Flink 提供统一的编程抽象,简化大数据应用开发,并在流处理方面表现卓越,广泛应用于实时监控、金融交易分析等场景。其架构包括 JobManager、TaskManager 和 Client,支持并行度、水位线、时间语义等基础属性。Flink 还提供了丰富的算子、状态管理和容错机制,如检查点和 Savepoint,确保作业的可靠性和一致性。此外,Flink 支持 SQL 查询和 CDC 功能,实现实时数据捕获与同步,广泛应用于数据仓库和实时数据分析领域。
6889 32
|
SQL 数据库
SQL中CASE WHEN THEN ELSE END的用法详解
SQL中CASE WHEN THEN ELSE END的用法详解
3296 2
|
SQL Oracle 关系型数据库
实时计算 Flink版操作报错合集之连接器换成2.4.2之后,mysql作业一直报错如何解决
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
465 3