我正在創建一個與我的學校夥伴關聯的類的項目,我應該爲某些函數創建拉取請求,但是我在創建類時遇到了一些問題並以一種可以編譯的方式覆蓋這些方法(我現在不需要編寫這些方法,這是項目,我只是需要編譯它)。我發現大多數方法正在(或至少編譯器不抱怨),但我感到困惑的幾件事情:編譯器要求可選方法從集合中被覆蓋
編譯器抱怨是可選的方法(如集和中的addAll)
雖然addAll方法被添加,但它抱怨說它沒有被覆蓋,雖然它是,並且當我爲它添加其他addAll方法時,我也得到了一個擦除錯誤。
我讀過一堆關於它,但我找不到一個正確的結論如何解決它。我只是使用Atom編寫我的代碼,而終端,沒有花哨的IDE(也許我應該學習一個)。
如果不清楚,我只是想找到可用方法的存根,而不是每個方法的全部答案,因爲這是類的項目。
// https://docs.oracle.com/javase/8/docs/api/java/util/List.html
import java.util.*;
import java.lang.reflect.*;
public class SkipList<E> implements List<E>
{
// compiler complaining, then added, although optional
public E set(int index, E element)
{
throw new IndexOutOfBoundsException();
}
// compiler complaining, then added, although optional
public boolean addAll(Collection <? extends E> c)
{
return true;
}
// Group 1
public boolean add(E e)
{
return true;
}
public void add(int index, E e)
{
}
public boolean addAll(Collection c)
{
return true;
}
public int indexOf(Object o)
{
int index = 0;
return index;
}
public int lastIndexOf(Object o)
{
int index = 0;
return index;
}
// Group 2
public boolean contains(Object o)
{
return true;
}
public boolean containsAll(Collection c)
{
return true;
}
public boolean equals(Object o)
{
return true;
}
public List<E> subList(int fromIndex, int toIndex)
{
List<E> sub = new SkipList<>();
return sub;
}
// Group 3
public boolean isEmpty()
{
return true;
}
public int size()
{
int size = 0;
return size;
}
public void clear()
{
}
public E get(int index)
{
throw new IndexOutOfBoundsException();
}
public E getQuantile(double quantile) // e.g. 0 = minimum, 0.5 = median, 1 = max
{
throw new IndexOutOfBoundsException();
}
// Group 4
public Iterator<E> iterator()
{
throw new IndexOutOfBoundsException();
}
public ListIterator<E> listIterator()
{
throw new IndexOutOfBoundsException();
}
public ListIterator<E> listIterator(int index)
{
throw new IndexOutOfBoundsException();
}
// Group 5
public E remove(int index)
{
throw new IndexOutOfBoundsException();
}
public boolean remove(Object o)
{
return true;
}
public boolean removeAll(Collection c)
{
return true;
}
public boolean retainAll(Collection c)
{
return true;
}
// Group 6
public int hashCode()
{
int hashCode = 0;
return hashCode;
}
public Object[] toArray()
{
Object[] arr = new Object[0];
return arr;
}
public <T> T[] toArray(T[] a)
{
return a;
}
}
這些方法**不**可選。 –
@ElliottFrisch有趣。我認爲API的可選操作是「可選操作」。有時間瞭解他們如何描述可選項。 :) –
「可選操作」意味着方法的實現可以拋出一個'UnsupportedOperationException'而不是實際執行該函數。這意味着,如果你說'List list = someMethodCall();'這樣你就不知道列表的確切類型,你必須小心使用'addAll'或其他可選操作,因爲它們可能不起作用。但是如果抽象的話,這些方法仍然必須被覆蓋。 –
ajb