Search code examples
javalistguava

Casting an ImmutableList to List


Although my research was going in circles, it looks like Google Guava's ImmutableList implements List. So I can cast it up to a List, right? I know it will throw an error if one of the List's modification methods are used, but is that all that can go wrong?

public List<Integer> getList() { 
    return ImmutableList.of(1,2,3);
}

Solution

  • If it implements List, there's no need to cast it to List. You can assign it to a List variable or pass it to a method that expects a List without casting.

    And, yes, calling any of the methods that modify a List would throw an exception, but it would happen regardless to whether or not you cast it to List.