2

I have various questions regarding maps:

  1. When iterating a Hashmap, there will be no guarantee about the iteration order. Now why is that?
  2. Why are Hashmaps faster than Treemaps?
  3. How do LinkedHashMaps work, how do they maintain the order? Is it because they have a doubly-linked list that contains the information about which entry is stored before and after an entry?

I've been reading through the API doc, but since I'm a beginner when it comes to programming I had some trouble understanding it.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Gekal
  • 47
  • 2
  • 2
    You should be more specific about what you don't understand. We might just give you the same explanations you already didn't get. – tnw Jul 01 '15 at 17:40
  • You need to review Data Structures. there are thousand of resources that will go into detail as to how each one works. – ScarletMerlin Jul 01 '15 at 17:41
  • 2
    As a primer you can read [this](https://en.wikipedia.org/wiki/Hash_table) and [this](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree), so that you'll understand how hash tables/maps and binary trees (specifically red-black trees used by TreeMap) work in general. As for the third question, the answer is: yes. :) – biziclop Jul 01 '15 at 17:41
  • Refer [this](http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/) – Madhan Jul 01 '15 at 17:45
  • 2
    possible duplicate of [Difference between HashMap, LinkedHashMap and TreeMap](http://stackoverflow.com/questions/2889777/difference-between-hashmap-linkedhashmap-and-treemap) – Madhan Jul 01 '15 at 17:47
  • 1
    @Madhan: This isn't quite a duplicate. At least, it doesn't feel like one to me. – Makoto Jul 01 '15 at 17:51

2 Answers2

5

When iterating a Hashmap, there will be no guarantee about the iteration order. Now why is that?

They're inserted not in order of when they occurred, but what value they hash to.

For example, suppose that we have a hash function h(x) which returns 127 for the string "Hello", and 12 for "Zebra". If we enter those keys into our hash map, the order in which they are read out is "Zebra" -> (whatever value attached), then "Hello" -> (whatever value attached).

This is apparent in the source code for HashMap:

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

Mind you, this is a simplified variation on what hashing actually does and represents. It could be the case that there is a collision on a hash value, and that collision needs to be addressed in some fashion. This is meant as primer; the key is inserted in order of its hash, but if your hash function has flaws or you don't have a good value for your object's hash, then you may run into aberrant behavior.

Why are Hashmaps faster than Treemaps?

A hash operation is not dependent on the size of the overall collection. Recall that h(x) only operates based on the single value we're trying to insert. If we're inserting elements into a TreeMap, we have to consider what natural ordering they're in - and this involves traversing the structure to find a spot to insert into, and may also involve rebalancing or reorganizing the structure to ensure that balance is preserved.

There's a lot more to the source for TreeMap's put method.

public V put(K key, V value) {
    Entry<K,V> t = root;
    if (t == null) {
        compare(key, key); // type (and possibly null) check

        root = new Entry<>(key, value, null);
        size = 1;
        modCount++;
        return null;
    }
    int cmp;
    Entry<K,V> parent;
    // split comparator and comparable paths
    Comparator<? super K> cpr = comparator;
    if (cpr != null) {
        do {
            parent = t;
            cmp = cpr.compare(key, t.key);
            if (cmp < 0)
                t = t.left;
            else if (cmp > 0)
                t = t.right;
            else
                return t.setValue(value);
        } while (t != null);
    }
    else {
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;
        do {
            parent = t;
            cmp = k.compareTo(t.key);
            if (cmp < 0)
                t = t.left;
            else if (cmp > 0)
                t = t.right;
            else
                return t.setValue(value);
        } while (t != null);
    }
    Entry<K,V> e = new Entry<>(key, value, parent);
    if (cmp < 0)
        parent.left = e;
    else
        parent.right = e;
    fixAfterInsertion(e);
    size++;
    modCount++;
    return null;
}

How do LinkedHashMaps work, how do they maintain the order? Is it because they have a doubly-linked list that contains the information about which entry is stored before and after an entry?

You can read the source for yourself, but the main takeaway here:

  • Keys are still grouped together in a hash structure to ensure their uniqueness.
  • The order in which they are inserted is preserved by a FIFO structure, like a linked list.

Think of it like this: you use the hash function to ensure that the key is unique, and if it is, you then immediately insert it and its value into the list. This way, both the ordering and the uniqueness are preserved.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • *If we enter those values into our hash map*. Are you talking about entering the hash values into the `HashMap` or the `String` values? Also do you mean *keys* instead of *values*? – Chetan Kinger Jul 01 '15 at 18:01
  • Let me go ahead and clarify that. Those should be keys, not values. – Makoto Jul 01 '15 at 18:02
-2

To keep it short : Maps and sets are generally unsorted data structures. If you want "sorted sets", you'd probably better use lists or arrays.

Your question is more about data structures rather than a really specific or java related programming problem, hence, you should start by reading about thoses. (sorry to post as an answer : commenting questions needs 50 rep)

Balmipour
  • 2,985
  • 1
  • 24
  • 28
  • 1
    You should have said that in comment.This is not a valid answer .It's a suggestion and it is not detailed enough – Madhan Jul 01 '15 at 17:46
  • You're also conflating sorting and ordering. A `HashMap` and a `HashSet` are *unordered* overall, but that's not to say you couldn't sort the data (or even order it). – Makoto Jul 01 '15 at 17:56
  • Not true either, e.g.. TreeMap vs HashMap, TreeSet vs HashSet. Also, if you need a set, why would you ever use Lists or Arrays? Membership in a Set is O(1) or O(LogN) for Set classes. Using Lists and Arrays as Sets are just simply a bad idea. – ylun.ca Jul 01 '15 at 18:25