this is my first attempt to a code doubly linked program in java:
This is my implementation of getting an iterator to getall items in the doubly linkedlist
public Object next() {
if(list.getSize()==0){
throw new NoSuchElementException();
}else{
current=current.getNext();
return current.getItem();
}
}
Please dont laugh at me but whatever I try I am getting
Cannot find symbol : symbol class: NoSuchElementException
I tried creating a class NoSuchElementException.java which extends Exception
Then I get
unreported exception NoSuchElementException; must be caught or declared to be thrown throw new NoSuchElementException();
I tried changing code to :
public Object next() throws NoSuchElementException {
Then I get
next() in ElementsIterator cannot implement next() in java.util.Iterator; overridden method does not throw NoSuchElementException
Can anybody point to where I got wrong. If this is not sufficient info to resolve this issue, please do tell me.
To fix the NoSuchElementException , it should be ensured that the underlying object contains more elements before using accessor methods that can throw the exception.
The NoSuchElementException in Java is thrown when one tries to access an iterable beyond its maximum limit. The exception indicates that there are no more elements remaining to iterate over in an enumeration.
Cause for NosuchElementException If you call the nextElement() method of the Enumeration class on an empty enumeration object or, if the current position is at the end of the Enumeration, a NosuchElementException is generated at run time.
You need to import java.util.NoSuchElementException
instead of creating your own.
The compiler is giving you a pretty good explanation. You are providing an implementation of the next()
method declared in Iterator, which has a signature of:
public Object next()
However, you have introduced your own checked exception called NoSuchElementException
, which required that you change the method signature to:
public Object next() throws NoSuchElementException
Now you are no longer implementing the method declared in the interface. You've changed the signature.
Anyways, there are a couple ways you can fix this:
Change your NoSuchElementException
class so that it inherits from RuntimeException instead of just Exception
. Then you don't need to add a throws
declaration to the method signature.
Get rid of your custom exception type and instead use Java's built-in NoSuchElementException, which already inherits from RuntimeException
. This is almost certainly the better option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With