LinkedList、HashSet 和 HashMap 之间的主要区别是什么?

Mik*_*hin 0 java

好吧,你不介意我写我的“测试”项目;首先,我创建了实现 AbstractMap 的类。

public class TestClass <K, V> extends AbstractMap <K, V> 
Run Code Online (Sandbox Code Playgroud)

TestClass 具有作为参数的私有 LinkedList(它是另一个实现 Map.Entry 的类:

private int size = 1000;
private LinkedList <InfoClass <K, V>> [] array = new LinkedList [size];
Run Code Online (Sandbox Code Playgroud)

之后,我创建了检查和替换重复项的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

这个方法形成了一组 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;
}
Run Code Online (Sandbox Code Playgroud)

好的,在 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);
}
Run Code Online (Sandbox Code Playgroud)

希望我解释正确。我有一个问题,如果它们以相同的方式工作,LinkedList 和 LinkedHashMap (HashMap) 之间有什么区别?非常感谢!

Epi*_*rce 5

如果多次添加相同的元素,LinkedList 可以多次包含相同的元素。

即使多次添加,HashSet 也只能包含一次相同的对象,但它不保留集合中的插入顺序。

即使多次添加,LinkedHashSet 也只能包含同一个对象一次,但它也保留了插入顺序。

HashMap 将一个值映射到一个键,键存储在一个集合中(所以它只能在集合中一次)。HashMap 不保留键集的插入顺序,而 LinkedHashMap 确实保留键的插入顺序。