Generic unmodifiableList

299 Views Asked by At

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?

2

There are 2 best solutions below

2
On

You can do this:

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

You need to do it like this:

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