UnsupportedOperationException when add item to ArrayList

2.1k views Asked by At

I have the below class which contains a list of bankAccounts. I have another traitement where I add many BankAccounts to a specific AssignmentIban with the addBankAccount method. But the problem I have this error java.lang.UnsupportedOperationException: null

public class AssignmentIban  {

    private List<BankAccount> bankAccounts;

    public void addBankAccount(BankAccount bankAccount) {
        if (this.bankAccounts== null || this.bankAccounts.isEmpty()) {
            this.bankAccounts= new ArrayList<>();
        }
        this.bankAccounts.add(bankAccount); // java.lang.UnsupportedOperationException: null
    }

}

java.lang.UnsupportedOperationException: null
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.test.AssignmentIban.addBankAccount(AssignmentIban.java:20)

1

There are 1 answers

0
Davide Lorenzo MARINO On

Probably the list is an immutable list, for example is obtained with Arrays.asList method:

Returns a fixed-size list backed by the specified array

In this case the implementation doesn't support method to modify the list and every temptative to invoke a method to modify the list generates an UnsupportedOperationException.

The UnsupportedOperationException is dedicated to the Collection framework to signal exactly this beahaviour:

Thrown to indicate that the requested operation is not supported. This class is a member of the Java Collections Framework.