抛出UnsupportedOperationException

因此,方法描述之一如下:

public BasicLinkedList addToFront(T data)此操作对排序列表无效。 将使用消息“排序列表的无效操作”生成UnsupportedOperationException。

我的代码是这样的:

public BasicLinkedList addToFront(T data) { try { throw new UnsupportedOperationException("Invalid operation for sorted list."); } catch (java.lang.UnsupportedOperationException e) { System.out.println("Invalid operation for sorted list."); } return this; } 

这是正确的做法吗? 我只是使用println()打印出消息,但是有不同的方法来生成消息吗?

您不希望在方法中捕获exception – 关键是让调用者知道不支持该操作:

 public BasicLinkedList addToFront(T data) { throw new UnsupportedOperationException("Invalid operation for sorted list."); } 

您可以将代码重写为这样

 public BasicLinkedList addToFront(T data) throws UnsupportedOperationException { if (this instanceof SortedList) { throw new UnsupportedOperationException("Invalid operation for sorted list."); }else{ return this; } } 

这基本上可以完成你所要求的。