無論誰寫這個任務應該已經添加Javadoc的方法,所以你會知道他們應該做什麼。
首先,界面名稱不正確,因爲它的行爲更像是Map
而不是List
。由於只有一個add()
方法,並且您有兩個(三個?)方法需要一個索引參數,並且賦值「像數組列表」一樣,所以我建議您按LinkedHashMap
的方式執行add()
,因爲該類是一個Map
保留插入順序的方式是ArrayList
。
您的實現應該可能將鍵/值對內部存儲在內部KeyValuePair
類的數組中。由於沒有關於性能的要求,所以具有關鍵值的方法應該只是進行順序搜索。
更新替代理論:密鑰類型K
被定義爲extends Comparable<K>
究其原因,是讓您可以撥打key1.compareTo(key2)
,或者更準確地說,這樣的陣列可以被排序,你可以做二進制搜索找到問題的關鍵。這意味着它的行爲更像TreeMap
而不是LinkedHashMap
。否則,我真的不明白爲什麼鑰匙需要是Comparable
。
所以,這裏是來自LinkedHashMap
和ArrayList
減少javadoc的接口,它假定插入順序,沒有排序:
/**
* 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的類型也將Comparable擴展到它自己。然後使用它的compareTo方法根據鍵將您的條目與其他條目進行比較 – iMBMT
您是對的,方向有些模糊。我們可以猜測,但這就是它的全部。爲什麼不問誰給了你任務? – yshavit