I have a get method for my singly linked list and they work fine but my instructor told me that he wants me to cut down on the code because I have too many special cases. Problem being is that when I try to cut out some parts of my code, the code no longer works as it's supposed to.
The code written from me:
public E get(int index) {
Node<E> f = first;
// If index is bigger / smaller than Linked List size throw IndexOutOfBounds
if (index > size || index < 0){
throw new IndexOutOfBoundsException();
}
// Index Less than size and is not the first or last node.
if (index < size && index > 0) {
for (int i = 0; i < index; i++) {
f = f.next;
}
return f.getValue();
}
// If the Linked List is empty + Index = 0 return null
if (first == null && index == 0) {
return null;
}
// If Linked List is not empty and index = 0 return first value
if (index == 0) {
return first.getValue();
}
// If index = end of list
if (index == size) {
return last.getValue();
}
// Return null if not found.
return null;
}
So he tells me that I'm putting too much thought into it and there are only two cases needed, if the index is valid or not valid; which I agree with him on, so I try to shorten my code to this:
Node<E> f = first;
// If index is bigger / smaller than Linked List size throw IndexOutOfBounds
if (index > size || index < 0){
throw new IndexOutOfBoundsException();
}
// Index Less than size and is not the first or last node.
if (index <= size && index >= 0) {
for (int i = 0; i < index; i++) {
f = f.next;
}
}
return f.getValue();
and for my test cases I'm using a Linked List with these values:
[Frank, George, Josh, Jim, Marry, Susie, John, Jim, Dakota, Levi, Jackson, Jeff, Walt, Matt]
and my test cases are as follows in my test class:
System.out.println("Get Method Test ----------------------------");
System.out.println("First Index: " + ll.get(0));
System.out.println("Last Index: " + ll.get(ll.size()));
System.out.println("'Middle' Index: " + ll.get(5));
System.out.println("Empty list with index of 0: " + llempty.get(0));
Which throws a NullPointerException
at the second test case of trying to get the last index:
Output:
First Index: Frank
Exception in thread "main" java.lang.NullPointerException
I need to be able to demonstrate the following:
Test cases: index of zero, index at end of list, index in “middle” of list, empty list with index 0, index too big, index too small
So I'm stuck here guys / gals, any help would be appreciated!