So my assignment requires that I implement an interface in one of my class. The interface is a generic Iterator, which I will have to override the hasNext() and next() methods. I'm getting an error when I try to assign the instance ArrayList iterator to the instance Iterator.
Here's my interface:
public interface Iterator <E>
{
boolean hasNext();
E next();
void remove();
}// end Iterator interface
And here's the class that implements that interface:
import java.util.*;
import java.io.*;
public class WordDatabase implements Iterator<String>
{
// Declaration
private List<String> aList;
private Iterator<String> aListIterator;
/**** Other Class Methods Here *****/
@SuppressWarnings("unchecked")
public void shuffle()
{
// Declaration
int rand;
String temp;
// Statement
// shuffling ArrayList
for(int i = 0; i < getAlist(); i++)
{
rand = (int)(Math.random() * getAlist() - 1);
// swapping two ArrayList entry
temp = aList.get(i);
aList.remove(i);
aList.add(i, aList.get(rand));
aList.remove(rand);
aList.add(rand, temp);
}
aListIterator = aList.iterator();
return;
}// end shuffle method
Eclipse is telling me that I need to cast aList.iterator()
to Iterator<String>
, but doing so throws an error java.util.AbstractList$Itr cannot be cast to Iterator
. Can someone help me figure this problem out?
You can not do that as both Iterator
objects belong to different packages.
You have to define your own List
interface as you did for Iterator
; Define a method iterator()
which returns object of your interface Iterator
.
What i understood from the exception is You have defined your own Interface as Iterator so now there would not be any relation with List. So you can't Cast.
The java.util.List.iterator
method returns an instance of java.util.Iterator
, and not your my.special.Iterator
interface. But you have declared the variable as my.special.Iterator
interface. Though they have the same simple name, they are actually different types, and Eclipse wants you to cast it, which you can't because they are not related.
You would have to implement your own special List class as well, or avoid using the iterator
method.
the Iterator<String> aListIterator
is your iterator interface and the iterator returned by aList.iterator();
is java.util.Iterator.
The names are same but packages different (i am presuming that). So you cant cast them. But to actually iterate a list using your iterator you need to extend the list and implement your iterator inside it. which is what your WordDatabase
class is trying to do. try to use an array in your class instead of a list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.