Search code examples
javasolid-principles

Arrays in java violates ISP?


The code below will throw UnsupportedOperationException in java :

String[] arr = {"a", "b", "c"};
List<String> list = Arrays.asList(arr);
list.add("d");

I'm a little confused isn't this an ISP violation ? Here class implements the List interface but can't implement its method add()


Solution

  • Yes, it does violate the Interface Segregation Principle, like any Unmodifiable collection. The designers of the Collections API could have created separate interfaces for write and read actions but decided to keep them together.

    One could argue that this list does confirm to the ISP -- it has the add() function -- but the thing that it does with that function is not what you expect. [EDIT, per @progman below: And the exception can be considered part of the interface, because it is documented.]

    Here is a related discussion on Software Engineering Stack Exchange.