Reputation: 45
I am working on a Linked Lists assignment for my OOP class, and have run into some trouble with a remove method. Our professor has asked us to write a method:
public Object removeElement(int index)
This takes an index, which is the location of the element that needs removed. It must return the data the deleted node contained as well. However, I am having trouble with getting the method to return the object it is removing. For some reason I keep getting the error that the method must return a result of type object. I have it returning an object, and I've gone through trial and error in various spots with no success. Here is my code:
public Object removeElement(int index)
{
ListIterator iterator = listIterator();
Object object;
//If the supplied index is less than zero, throw an exception.
if(index < 0)
{
IndexOutOfBoundsException ex = new IndexOutOfBoundsException();
throw ex;
}
else
{
for(int i = 0; i <= index; i++)
{
if(!iterator.hasNext())
{
IndexOutOfBoundsException ex = new IndexOutOfBoundsException();
throw ex;
}
else
{
if(i == index)
{
object = iterator.next();
iterator.remove();
return object;
}
else
{
iterator.next();
}
}
}
}
}
Upvotes: 0
Views: 2968
Reputation: 5399
Firstly do not use iterator from java LinkedList it is Doubly linked list , I think professor wants to see how you implement remove functionality for LikedList data structure.
Secondly make loop and condition where i+1 == index
in this place, save current element for return like Node returnElement = curent.next;
and make delete manipulation curent.next = curent.next.next;
Upvotes: 1
Reputation: 32
Pls post listIterator() method implementation and the error message that you are getting. Note:> You have to manage the size of the list using an class variable such as an integer. So you dont have check !iterator.hasNext(), instead compare index with current size.
Upvotes: 0
Reputation: 1500385
You have it returning an object if i == index
. But the compiler doesn't know that the loop will actually always end at that point. It's looking at the bottom of the loop and thinking "What do we want to return if we get here?"
I would actually restructure your code to:
if (index < 0)
{
// No need for a separate variable
throw new IndexOutOfBoundsException();
}
// No need for an else block
ListIterator iterator = listIterator();
Object current = null;
for (int i = 0; i <= index; i++)
{
// Note: assuming you expose the size(), you could check this up front...
if(!iterator.hasNext())
{
throw new IndexOutOfBoundsException();
}
current = iterator.next();
}
iterator.remove();
return current;
Now you always call remove
and return when you've called next()
the given number of times, because that's when the loop will end other than via an exception.
Upvotes: 3