Returning const reference of an arraylist

后端 未结 4 1733
小鲜肉
小鲜肉 2021-02-19 04:22

I really admire java features and I don\'t want to give up using it for the next problem:

I have a class that might be inherited, and inside of it is a private Arr

4条回答
  •  野性不改
    2021-02-19 05:00

    Wrap the return value with java.util.Collections.unmodifiableList. It does not make a copy of the data, but wraps the original list, and delegates read-only operations to the underlying list. Operations which would modify the list are rejected at runtime via UnsupportedOperationException.

    Your

    return arrayList;
    

    becomes

    return Collections.unmodifiableList(arrayList);
    

    Unfortunately the read-only constraints won't be enforced by the compiler. They will, however, be enforced at runtime.

    You also have available to you: unmodifiableSet, unmodifiableMap, unmodifiableCollection, unmodifiableSortedSet, and unmodifiableSortedMap. And if these are not enough, you can still take inspiration from this general design approach, and create your own custom read-only wrapper classes.

提交回复
热议问题