【发布时间】:2017-06-18 11:23:41
【问题描述】:
好吧,你不介意我会写我的“测试”项目; 首先,我创建了实现 AbstractMap 的类。
public class TestClass <K, V> extends AbstractMap <K, V>
TestClass 具有作为参数的私有 LinkedList(它是另一个实现 Map.Entry 的类:
private int size = 1000;
private LinkedList <InfoClass <K, V>> [] array = new LinkedList [size];
之后,我创建了检查和替换重复项的方法:
public V put (K key, V value){ // Void doesn't work, therefore we need to return any value;
V temp = null;
boolean found = false;
int index = Math.abs(key.hashCode()) % size;
if (array[index] == null)
array[index] = new LinkedList <InfoClass <K, V>> (); // If the specified member of array is null, create new member;
LinkedList <InfoClass <K, V>> list = array[index];
InfoClass <K, V> info = new InfoClass <K, V> (key, value);
ListIterator <InfoClass <K, V>> it = list.listIterator();
while (it.hasNext()){
InfoClass<K, V> temp2 = it.next(); // Create a temp instance;
if (temp2.getKey().equals(key)){ // If there is a duplicate of value, just replace by new one;
found = true;
temp = temp2.getValue();
it.set(info);
break;
}
}
if (!found) // if there is not a duplicate, add new one;
array[index].add(info);
return temp;
}
Next 方法返回一个值,否则如果数组的成员不存在则返回 null:
public V get (Object key){ // The parameter K doesn't work;
int index = Math.abs(key.hashCode()) % size;
if (array[index] == null)
return null;
else
for (InfoClass <K, V> info : array[index])
if (info.getKey().equals(key))
return info.getValue();
return null;
}
该方法形成一组AbstractMap:
public Set<java.util.Map.Entry<K, V>> entrySet() {
Set <Map.Entry<K, V>> sets = new HashSet <Map.Entry<K, V>> ();
for (LinkedList <InfoClass<K, V>> temp1 : array){
if (temp1 == null)
continue;
else{
for (InfoClass<K,V> temp2 : temp1)
sets.add(temp2);
}
}
return sets;
}
好的,在 main 方法中创建新对象:
public static void main (String [] args){
TestClass <Integer, String> TC = new TestClass <Integer, String> ();
TC.putAll(CollectionDataMap.newCollection(new Group.Ints(), new Group.Name(), 10));
System.out.println(TC);
System.out.println(TC.get(1));
TC.put(1, "Hello this world");
System.out.println(TC);
}
希望我解释正确。我有一个问题,如果 LinkedList 和 LinkedHashMap (HashMap) 的工作方式相同,它们有什么区别? 非常感谢!
【问题讨论】:
-
A
LinkedHashMap基本上是一个HashMap,其中包含一个贯穿所有条目的双向链表。它是列表和地图之间的混合体。在发布如此广泛的问题之前,您应该查阅 JavaDoc。
标签: java