Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend ImmutableList.of() by another List

I want to simplify existing code that is related to ImmutableList.of() functionality

I alreaday tried to optimize the creation of the second List by eliminating the "new..." constructor, but of course I couldnt extend a immutable list by calling .add();

Current code:

static final ImmutableList<ProductCodeEnum> PRODUCTS = ImmutableList.of(ProductCodeEnum.A, ProductCodeEnum.B, ProductCodeEnum.C);


static final ImmutableList<ProductCodeEnum> PRODUCTS_EXTENDED_LIST = new ImmutableList.Builder<ProductCodeEnum>().addAll(PRODUCTS)
.add(ProductCodeEnum.D)
.add(ProductCodeEnum.E)
.build();

Expected code like:

static final ImmutableList<ProductCodeEnum> PRODUCTS = ImmutableList.of(ProductCodeEnum.A, ProductCodeEnum.B, ProductCodeEnum.C);


static final ImmutableList<ProductCodeEnum> PRODUCTS_EXTENDED = PRODUCTS + ImmutableList.of(ProductCodeEnum.D, ProductCodeEnum.E);
like image 990
DerBenniAusA Avatar asked Apr 03 '19 12:04

DerBenniAusA


People also ask

Can you add to ImmutableList?

add(element) " is because this method is designed to be able to add elements to ImmutableList s. Those are, quite obviously, immutable (if you look, their native add method throws an UnsupportedOperationException ) and so the only way to "add" to them is to create a new list.

How do you make an Arraylist immutable?

No, you cannot make the elements of an array immutable. But the unmodifiableList() method of the java. util. Collections class accepts an object of the List interface (object of implementing its class) and returns an unmodifiable form of the given object.

How do you make a collection immutable?

In Java 8 and earlier versions, we can use collection class utility methods like unmodifiableXXX to create immutable collection objects. If we need to create an immutable list then use the Collections. unmodifiableList() method.


1 Answers

I think you use Guava ImmutableList?

In that case your code would look like this:

static final ImmutableList<ProductCodeEnum> PRODUCTS = ImmutableList.of(ProductCodeEnum.A, ProductCodeEnum.B, ProductCodeEnum.C);

static final ImmutableList<ProductCodeEnum> PRODUCTS_EXTENDED = ImmutableList.builder().addAll(PRODUCTS).add(ProductCodeEnum.D, ProductCodeEnum.E).build();
like image 186
mind_ Avatar answered Sep 22 '22 10:09

mind_