Returning const reference of an arraylist

后端 未结 4 1736
小鲜肉
小鲜肉 2021-02-19 04:22

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 Arr

4条回答
  •  遥遥无期
    2021-02-19 05:12

    You could also use Google Guava's immutable collections. In this case, you would store an ImmutableList in your field.

    Of course, if your class needs to modify this list internally, using ImmutableList might turn out to be a bad idea, since you'll need to create a new ImmutableList instance and reassign it to the field each time...

    But it's perfect when you know the List won't change after object construction.

    Immutable example (list won't change after object construction)

    @Immutable
    public final class Foo {
    
        @Nonnull
        private final ImmutableList list;
    
        public Foo(@Nonnull List list) {
            // you could also compute the appropriate list here
            // before assigning it to the field
            this.list = ImmutableList.copyOf(list);
        }
    
    
        public ImmutableList getList() {
            return list;
        }
    }
    

    Mutable example (list may only be modified using the setter)

    public class Foo {
    
        @Nonnull
        private ImmutableList list = ImmutableList.of();
    
        public ImmutableList getList() {
            return list;
        }
    
        public void setList(@Nonnull List list) {
            this.list = ImmutableList.copyOf(list);
        }
    }
    

    Remarks

    • I know it's often advised to make methods return the most generic type possible (List in this case), but I prefer to declare my getter's return type as an ImmutableList, because it acts as documentation (no need to document the returned list's immutability in the Javadoc) and as an API contract. It's like saying "I guarantee this list to be immutable, you do not have to worry or defensively copy it". And it is very concise.
    • ImmutableList.copyOf() is great, since it automatically rejects null lists (by throwing NullPointerException). It also rejects null elements. And it won't copy the source list if it's already an ImmutableList, which avoids useless object instantiation.
    • In the second example, I initialize the field to an empty ImmutableList using ImmutableList.of(), because it's a good practice to return empty collections instead of null values (Null Object pattern). You might think that this creates needless object instantiation, but ImmutableList.of() actually returns a singleton.

提交回复
热议问题