链表insert方法哪里抛异常
Where to throw the exception in the insert method of a linked list
我这里有一个插入方法,它应该在链表无法添加更多节点时抛出 ListOverFlowException。我不知道在代码的什么地方可以抛出异常。
public void insert(D data) throws ListOverflowException {
Node<D> iterator = new Node<>(data);
if(startOfNode == null) {
startOfNode = iterator;
endOfNode = iterator;
iterator.setNext(startOfNode);
}
endOfNode.setNext(iterator);
endOfNode = iterator;
endOfNode.setNext(startOfNode);
// where do I put the ListOverflowException?
//throw new ListOverflowException("Error! Can't add any more nodes");
sizeOfList++; // updates the size of the node
}
该方法何时无法再插入更多节点?
您的列表中应该有一个 maxSize
值(硬编码或传递给 class 的构造函数)。
然后你可以用它来检查sizeOfList
。
class YourLinkedList<D> {
private Node<D> startOfNode, endOfNode;
private int sizeOfList;
private int maxSize;
//Passing max size
public YourLinkedList(int size) {
this.maxSize = size;
}
....
public void insert(D data) throws ListOverflowException {
if (sizeOfList == maxSize) {
throw new ListOverflowException("Error! Can't add any more nodes");
}
//your current code
}
}
或者您可以将其设为常量。
class YourLinkedList {
private int maxSize = 10;
//rest of code
}
我这里有一个插入方法,它应该在链表无法添加更多节点时抛出 ListOverFlowException。我不知道在代码的什么地方可以抛出异常。
public void insert(D data) throws ListOverflowException {
Node<D> iterator = new Node<>(data);
if(startOfNode == null) {
startOfNode = iterator;
endOfNode = iterator;
iterator.setNext(startOfNode);
}
endOfNode.setNext(iterator);
endOfNode = iterator;
endOfNode.setNext(startOfNode);
// where do I put the ListOverflowException?
//throw new ListOverflowException("Error! Can't add any more nodes");
sizeOfList++; // updates the size of the node
}
该方法何时无法再插入更多节点?
您的列表中应该有一个 maxSize
值(硬编码或传递给 class 的构造函数)。
然后你可以用它来检查sizeOfList
。
class YourLinkedList<D> {
private Node<D> startOfNode, endOfNode;
private int sizeOfList;
private int maxSize;
//Passing max size
public YourLinkedList(int size) {
this.maxSize = size;
}
....
public void insert(D data) throws ListOverflowException {
if (sizeOfList == maxSize) {
throw new ListOverflowException("Error! Can't add any more nodes");
}
//your current code
}
}
或者您可以将其设为常量。
class YourLinkedList {
private int maxSize = 10;
//rest of code
}