Тот, кто написал это задание, должен добавить Javadoc к методам, чтобы вы знали, что они должны делать.
Во-первых, интерфейс плохо назван, поскольку он ведет себя скорее как Map
, чем List
. Поскольку существует только один метод add()
, и у вас есть два (три?) Метода, которые принимают индексный параметр, а присваивание называется «как список массивов», я бы предложил вам реализовать add()
так, как это делает LinkedHashMap
, потому что этот класс является Map
, который сохраняет порядок вставки так, как ArrayList
будет.
Ваша реализация должна, вероятно, хранить пары ключ/значение внутри внутри массива внутреннего класса KeyValuePair
. Поскольку требования к производительности не требуются, методы с ключевым значением должны просто выполнять последовательный поиск.
Update Альтернативная теория: Причина тип ключа K
определяется как extends Comparable<K>
, поэтому вы можете позвонить key1.compareTo(key2)
, точнее, так что массив может быть отсортирован, и вы можете сделать бинарный поиск, чтобы найти ключ. Это означает, что он ведет себя как TreeMap
, чем LinkedHashMap
. В противном случае я действительно не вижу причины, по которой ключ должен быть Comparable
.
Итак, вот интерфейс с пониженным Javadoc из LinkedHashMap
и ArrayList
, что предполагает порядок вставки, не отсортирован:
/**
* This list defines the iteration ordering, which is normally the
* order in which keys were inserted into the list (insertion-order).
* Note that insertion order is not affected if a key is re-inserted into the list.
*/
public interface List<K extends Comparable<K>,V> {
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old value is replaced.
*
* @return the previous value associated with key, or null if there was no mapping for key.
*/
public abstract boolean add(K key,V value);
/**
* Removes the mapping for the specified key from this map if present.
*
* @return the previous value associated with key,
* or null if there was no mapping for key.
*/
public abstract V remove(K key);
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their indices).
*
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
*/
public abstract V remove(int n);
/**
* Removes the first element in this list.
* Same as remove(0).
*/
public abstract V remove();
/**
* Returns the value to which the specified key is mapped,
* or null if this map contains no mapping for the key.
*/
public abstract V lookup(K key);
/**
* Returns the number of key-value mappings in this list.
*/
public abstract int size();
/**
* Returns the element at the specified position in this list.
*
* @throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
*/
public abstract V get(int n);
}
У меня возникли проблемы следующие, V>, что именно это делает ? –
Вы заставляете тип вашего K также распространяться по сравнению с самим собой. вы затем используете метод compareTo для сравнения вашей записи с другой записью на основе ключей – iMBMT
Вы правы, направления немного расплывчаты. Мы могли бы предположить, но это все, что было бы. Почему бы не спросить, кто дал вам задание? – yshavit