2

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()

LightSouls
  • 55
  • 7

2 Answers2

4

The List.add() method is defined as an optional operation:

boolean add(E e)

Appends the specified element to the end of this list (optional operation).

And further down it defines when it throws an UnsupportedOperationException:

Throws:

UnsupportedOperationException - if the add operation is not supported by this list

So the implementation (returned by Arrays.asList()) is doing what is "allowed" to do based on the specification of the java.util.List interface.

Progman
  • 16,827
  • 6
  • 33
  • 48
2

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.

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
  • Progman is conflating different principles. His argument is unrelated to the ISP. Your first paragraph is correct. – jaco0646 Jun 30 '23 at 18:55