padawan
padawan

Reputation: 1315

A class attribute type of List which is not modifiable by accessor

Consider the following class:

class Foo
{
  private List<Integer> all;
  private Set<Integer> distinct;
  public List<Integer> getAll()
  {
    return all;
  }
  public void add(Integer i)
  {
    all.add(i);
    distinct.add(i);
  }
}

I don't want bar to be modified like so:

foo.getAll().add(3);

instead, I want to force my own add() procedure.
Is there a way to do this?

Upvotes: 0

Views: 103

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

You can make getAll() returning an unmodifiable list. You can think it like if it was returning a view, so the list will only be in read-only mode.

Any calls that will try modify the list returned will throw an UnsupportedOperationException.

public List<Integer> getAll(){
    return Collections.unmodifiableList(all);
}

Upvotes: 4

Related Questions