Вопрос

I am new to immutablelist and try to understand it better. As far as I understand once you have the immutable list in object it cannot be modified. but I am slightly confused as it used in the pojo.

Can I have immutableList as an attribute of pojo and define getter / setter of it ? If I do that, what will be implication of doing it.

Это было полезно?

Решение

You can use it in POJOs, yes. However, with collections and POJOs in general you should be careful.

Here is what you should do if your immutable list is an instance field:

// list is immutable
public List<X> getList() { return list; }
public void setList(final List<X> list) { this.list = ImmutableList.copyOf(list); }

All too often, in beans code, using a non immutable collection, you will see that:

// list is mutable -- DON'T DO THAT
public List<X> getList() { return list; }
public void setList(final List<X> list) { this.list = list; }

But this is very, very unsafe:

  • you return a reference to the list; this reference can be modified (ImmutableList does not have this problem!);
  • you set a new reference to the list, which can also be modified.

What should be done is:

// list is mutable
public List<X> getList() { return Collections.unmodifiableList(list); }
public void setList(final List<X> list) { this.list = new ArrayList<>(list); }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top