无论谁写这个任务应该已经添加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