dont work post and delete req requests in spring boot java.lang.UnsupportedOperationException: null

Viewed 25

I want to add a regular user to the list. I use Postman for this, the request body comes, but when adding, such an error occurs.

    @PostMapping
    public Developer create(@RequestBody Developer developer) {
        System.out.println(developer);
        this.DEVELOPERS.add(developer);
        return developer;
    }
2022-09-11 23:19:53.444 ERROR 30036 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.UnsupportedOperationException] with root cause

java.lang.UnsupportedOperationException: null
    at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) ~[na:na]
    at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147) ~[na:na] ...
2 Answers

As the error log, you're using the immutable collections it means that does not allow you to add the new element. Ex:

List<String> flowers = Arrays.asList("flower1", "flower2", "flower3"); 
flowers.add("new flower");

In this example, the Arrays.asList return list flowers it's a fixed list that does not allow you to add new flower -> exception will be thrown

Fix for this problem is to Use linkedList

Create a LinkedList, which supports faster remove.

List list = new LinkedList(Arrays.asList(split));

Related