com.google.web.bindery.autobean.vm.Configuration#setCategories(): unneeded creation of an array list?

52 views
Skip to first unread message

Andreas Kohn

unread,
Nov 14, 2014, 7:14:08 AM11/14/14
to google-web-tool...@googlegroups.com
Hi,

While trying to find the cause for a very odd NPE I noticed that Configuration#setCategories() is implemented like this

    public Builder setCategories(Class<?>... categories) {
      toReturn.categories =
          Collections.unmodifiableList(new ArrayList<Class<?>>(Arrays.asList(categories)));
      return this;
    }

Could someone explain why there is an explicit creation of the ArrayList done there? Both the result of Arrays.asList() and a java.util.ArrayList implement
RandomAccess, so for Collections#unmodifiableList() nothing really should change there.

Regards,
--
Andreas

Thomas Broyer

unread,
Nov 14, 2014, 8:27:46 AM11/14/14
to google-web-tool...@googlegroups.com
This is legal Java:

Class<?>[] classes = new Classes<?>[] { foo, bar };
builder.setCategories(classes);
classes[1] = baz;

This explicit copy prevents the builder (actually and more importantly its toReturn) from being modified from the outside: toReturn.categories is guaranteed to contain foo and bar, and not baz.

This is a standard pattern. Not doing the copy would actually be flagged as a possible source of error by things like Checkstyle and/or Findbugs (can't remember which ones flags this).

Andreas Kohn

unread,
Nov 18, 2014, 5:54:16 AM11/18/14
to google-web-tool...@googlegroups.com
Hi,

Thanks! I missing the minor detail of the ArrayList constructor actually cloning the array.

Reply all
Reply to author
Forward
0 new messages