donturner
donturner

Reputation: 19146

How can I create an ImmutableList as a member variable?

I need to create an ImmutableList as a member variable.

Here's what I tried:

  private List<String> stringList = Arrays.asList("a", "b", "c");
  private ImmutableList<String> stringList2 = Collections.unmodifiableList(stringList);

This fails to compile with the error:

FakeRemoteDataStore.java:59: error: incompatible types: no instance(s) of type variable(s) T exist so that List<T> conforms to ImmutableList<String>
  private ImmutableList<String> stringList2 = Collections.unmodifiableList(stringList);
                                                                          ^
  where T is a type-variable:
    T extends Object declared in method <T>unmodifiableList(List<? extends T>)

How can I create an ImmutableList as a member variable?

Upvotes: 0

Views: 255

Answers (2)

donturner
donturner

Reputation: 19146

ImmutableList is part of Guava, so you can just do:

private ImmutableList<String> stringList = ImmutableList.of("a", "b", "c");

Upvotes: 1

Deepak Patankar
Deepak Patankar

Reputation: 3282

You can use copyOf function from ImmutableList

ImmutableList<String> stringList2 = ImmutableList.copyOf(stringList);

Upvotes: 1

Related Questions