I have a get method for my only linked list and they work fine, but my instructor told me that he wants me to shorten the code because I have too many special cases. The problem is that when I try to cut some parts of my code, the code no longer works as intended.
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;
}
Therefore, he tells me that I delve too much into this, and only two cases are needed if the index is valid or invalid; with which I agree with him, so I'm trying to shorten the 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 use a Linked List with these values:
[Frank, George, Josh, Jim, Groom, Susie, John, Jim, Dakota, Levy, Jackson, Jeff, Walt, Matt]
and my test cases in my test class are as follows:
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));
a NullPointerException :
:
First Index: Frank
Exception in thread "main" java.lang.NullPointerException
:
: , , "" , 0, ,
, /, !