I have a Foo
class that extends AbstractList
and implements List
. This class implements some of the List
methods, but some just throw UnsupportedOperationException
.
toArray
is one of the later and while the compiler doesn't complain about other not really implemented methods, it complains about the toArray
with error:
Class must either be declared abstract or implement abstract method toArray(T[]) in List
.
public class Foo extends AbstractList implementst List {
...
public <T> T[] toArray(T[] a) throws UnsupportedOperationException {
throw new UnsupportedOperationException(error);
}
}
What is wrong here and why the compiler still thinks the toArray(T[])
method is not implemented?
Since you are using generic method public T[] toArray(T[] a), you should add parameter to class signature and make it extend and implement parameterized class and interface respectively, not the raw ones. Then it will compile:
public class Foo<T> extends AbstractList<T> implements List<T> {
@Override
public <E> E[] toArray(E[] a) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Error!");
}
...
}
This code compiles :
import java.util.AbstractList;
import java.util.List;
public class Foo extends AbstractList implements List {
@Override
public Object[] toArray(Object[] a) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object get(int index) {
// TODO Auto-generated method stub
return null;
}
@Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
}
If you use java.util
package.
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.