1

I wrote:

this.array = (X[]) Array.newInstance(init.getClass(), size);

// ...

public List<X> get()  {        
    return Collections.<X>unmodifiableList(this.array);
}

But I get the error:

unmodifiableList in Collections cannot be applied to (X[])

How can I create a generic unmodifiable list?

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Skywooo
  • 87
  • 6
  • `return Collections.unmodifiableList(new ArrayList<>());` – Lino Jul 27 '17 at 08:32
  • @Lino You mean `Collections.emptyList()`? – shmosel Jul 27 '17 at 09:28
  • @shmosel as I read again the comment I've written, it seems quite wrong to me, as OP probably has a populated array and not an empty one. But if he does want to return an empty list your approach is better – Lino Jul 27 '17 at 09:34

2 Answers2

2

You need to do it like this:

public List<X> get()
{
    List<X> modifiableList = Arrays.asList( this.array );
    return Collections.unmodifiableList( modifiableList );
}
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
1

You can do this:

public List<X> get()  {
    return Collections.unmodifiableList(Arrays.asList(this.array));
}
alaster
  • 3,821
  • 3
  • 24
  • 32