Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning const reference of an arraylist

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 ArrayList arr; So the setter function is ok , but the getter function return arr; returns the reference to that variable which anyone capable of editing that whole array which I don't want and private wouldn't make any sense !

In C++ I would just return const arr; and it would return constant reference to the variable.

I so much need the variable not to be cloned or manually copied because there are so many calculations that require to (READ ONLY the variable) WHY there is no const returning in java ???? is there any way I could escape copying ?

p.s (final ArrayList<Integer> arr;) isn't an option cause that array always changes size or element values.

If I couldn't find a fix to that I'm threatening to go back to C++ or make everything public and you should never get my software :D


EDIT: one more important question: Am I asking for something that's not good (Software engineering wise) I mean if JAVA creators thought of not having const reference (returning Read only references) then I must be asking for something that can be handled in other way. or my program design is wrong I'm so confused.

like image 603
Ismail Marmoush Avatar asked Nov 24 '10 00:11

Ismail Marmoush


2 Answers

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.

like image 75
Mike Clark Avatar answered Oct 04 '22 13:10

Mike Clark


:) You have several options:

  • Don't expose getter, provide only methods which are allowed to call, e.g.

    public void addToList(Object arg) { this.arr.add(arg);}

  • Return immutable object:

    public List getArr() { return Collections.unmodifiableList(this.arr); }

like image 39
andbi Avatar answered Oct 04 '22 11:10

andbi