-1

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)

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Aymen Kanzari
  • 1,765
  • 7
  • 41
  • 73
  • 6
    Is it possible that bankAccounts is already initialized to a List instance that does not support adding? If not, why don't you initialize `bankAccounts` in the declaration? `private List bankAccounts = new ArrayList<>();` – VaiTon Apr 15 '22 at 13:40
  • `this` is redundant – g00se Apr 15 '22 at 13:43
  • 2
    Please [edit] your question to include the full complete error message you get, including the stacktrace. If possible, add a [mcve]. – Progman Apr 15 '22 at 13:47
  • Even stronger, a [mre] is required for this case. – Mark Rotteveel Apr 15 '22 at 14:15
  • Could you please add code which you execute when you get this error? The code (or some test, probably) where you call `addBankAccount`? – Sve Kamenska Apr 15 '22 at 20:45
  • Check the code which is calling addBankAccount method. May be it is passing immutable list to this method – Chetan Ahirrao Apr 16 '22 at 07:15

1 Answers1

2

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.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56