I have an insert method here that is supposed to throw a ListOverFlowException when the linked list cannot add any more nodes. I don't know where in the code I can throw the exception.
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
}
CodePudding user response:
When does the method cannot insert any more nodes?
You should have a maxSize
value in your list (either hard coded or passed to the constructor of your class).
Then you can use it to check against the 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
}
}
Or you can just make it a constant.
class YourLinkedList {
private int maxSize = 10;
//rest of code
}