0

I have 4 functions with same get...() method, and I only change the name or identifier, but I've got different result with the fourth which is when to adding new item to list, it throws java.lang.UnsupportedOperationException. I assure you, I've already double checked all 4 functions and their relations, but have no idea why the fourth function like this.

public List<PropertyAttribute> getAttributes() {
    if (selectedCode == null)
        return null;

    Criteria criteria = this.propertyAttributeDAO.createCriteria();
    FilterUtils.byField(criteria, "propertyCode", this.selectedCode, true);
    List<PropertyAttribute> list = criteria.list();

    if (isNewAttribute()) {
        list.add(0, this.curAttribute); //this line that throws exception
    }

    return list;
}

UPDATE STACK TRACE:

Caused by: java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(AbstractList.java:148)
        at bos.web.pages.instrument.ViewProperty.getAttributes(ViewProperty.java:654)
        at $InternalPropertyConduit_237587e282284.get(Unknown Source)
        at org.apache.tapestry5.internal.bindings.PropBinding.get(PropBinding.java:59)
Hobas Matius
  • 61
  • 2
  • 13
  • 4
    Can you post the whole stackTrace? It may also be interesting to know which `List` implementation `criteria.list()` produces – Aaron May 02 '17 at 08:24
  • I would guess like @nbokmans that the `criteria.list()` use a `Arrays.asList()` (or equivalent) returning an instance that don't support the `add` operation. – AxelH May 02 '17 at 08:27
  • 1
    You have your answer then, see [AbstractList documention](https://docs.oracle.com/javase/7/docs/api/java/util/AbstractList.html), it will be quite obvious what is the problem. And the solution as been given. – AxelH May 02 '17 at 08:52
  • @AxelH thanks, will see it. – Hobas Matius May 02 '17 at 09:25

1 Answers1

1

Unless it's clearly documented, don't assume it's safe to modify a list you received from another method. Even if it doesn't throw an exception, it may be altering critical state (if it's not implemented safely). Copy it to a new list and you can do whatever you like:

List<PropertyAttribute> list = new ArrayList<>(criteria.list());
shmosel
  • 49,289
  • 6
  • 73
  • 138