-3

trying to find the best way to do the "TODO's" for my add method. need to handle the special case where we are adding to the beginning of the list (index = 0) and need to handle the special case where the list is empty and index = 0

here is the method:

 public void add(int index, T item) throws IllegalArgumentException {

    if (index < 0 || index > size) {
        throw new IllegalArgumentException();

    } else {

        // TODO need to handle the special case where we are adding 
        // to the beginning of the list (index = 0)

        // TODO need to handle the special case where the list is empty 
        // and index = 0

        int counter = 0;

        Node<T> current = head;
        while (counter < index-1) {
            counter++;
            current = current.next;
        }

        Node<T> newNode = new Node(item);
        newNode.next = current.next;
        current.next = newNode;

        size++;
       }
   }
Progamminnoob
  • 293
  • 3
  • 4
  • 14

1 Answers1

0

For the 0 case:

if (index == 0) {
    Node<t> newNode = new Node(item);
    newNode.next = head
    head = newNode
    return;
}

It will work equally well if the list is empty (I assume that head is null), so you don't need additional if statement to check that.

I'd suggest you reading this and that tutorial.

Also, you don't need else statement after the first if. If exception is thrown, no code after that will be executed. So for clarity, instead of writing:

void someMethod() {
    if (condition) {
        throw new Exception();
    }
    else {
        // rest of the function here
    }
}

You can simply write:

void someMethod() {
    if (condition) 
        throw new Exception();

    // rest of the function here, no redundant indentation
}

Consider returning this object from the method. It will allow you to do method chaining. I don't know how your class is called, so in my example I'll call it MyList.

public MyList<T> add(int index, T item) {
    // method implementation
    return this;
}

And then usage, instead of:

MyList<Integer> myList = new MyList<>();
myList.add(0, 1);
myList.add(0, 2);
myList.add(0, 3);

You will be able to write, with the same result:

MyList<Integer> myList = new MyList<>();
myList.add(0, 1)
      .add(0, 2)
      .add(0, 3);
Community
  • 1
  • 1
Jezor
  • 3,253
  • 2
  • 19
  • 43