[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[p2-dev] Arrays versus List and immutability

On the call today we discussed pros and cons of using arrays versus collections. I'd like to address that briefly.

An IU must not change so whatever it returns must be read only. But todays implementation does this:

    public IRequiredCapability[] getRequiredCapabilities() {
        return requires;
    }

which means that in theory I can do:

   IRequiredCapability[] caps = iu.getRequiredCapabilities();
   if(caps.length > 0)
      caps[0] = foobar;

and change the content of the IU. In order to make it truly read-only, we must change into:

    public IRequiredCapability[] getRequiredCapabilities() {
        return (IRequiredCapability[])requires.clone();
    }

which is fairly expensive. What happens if we instead change the API so that the IU returns a List? We need a read-only List implementation that is backed by an array. The implementation is about 20 lines of code and the only field is the array, so it's very lightweight. The fields in the InstallableUnit doesn't need to change at all which means that its memory consumption wouldn't change either.

    public List<IRequiredCapability> getRequiredCapabilities() {
        return new ImmutableArrayList(requires);
    }

No copy needed. The ImmutableList protects the array. This is a much cheaper way to achieve immutability. If we're willing to sacrifice some memory, the requires field could of course change to store the list itself.

Regards,
Thomas Hallgren