HashMap

Status
Nicht offen für weitere Antworten.

babuschka

Top Contributor
Java:
package map;

import java.util.*;

public class Main {

    public static void main(String[] args) {

        HashMap h = new HashMap();

              h.put("A", "holla@yahoo.de");
        h.put("B", "ihallo@gmx.de");
        h.put("C", "g@yahoo.de");
        h.put("Cino", "f@hotmail.de");
        h.put("Lulu", "lulu@yahoo.de");




        Iterator it = h.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            System.out.println((String) entry.getKey() + "-->" + (String) entry.getValue());
        }
    }
}

Ausgabe:

Cino-->f@hotmail.de
A-->holla@yahoo.de
B-->ihallo@gmx.de
C-->g@yahoo.de
Lulu-->lulu@yahoo.de

Nach was wird es denn sortiert? Also Alphabetisch oder umgekehrt wird es nicht sortiert.


Außerdem was macht die Zeile:


Java:
Map.Entry entry = (Map.Entry) it.next();

Vielen dank im Voraus.
 
Zuletzt bearbeitet von einem Moderator:

javimka

Top Contributor
Ich habe mir mal die Methode put() von HashMap angesehen. Darin wird ein Hash-Wert für den key berechnet. Als erstes produziert key.hasCode() einen Hash-Wert, welcher dann mit der Methode hash() von HashMap wieder verändert wird. Danach berechnet die Methode indexFor(int h, int length) mit diesem Hash-Wert den Index im Array Entry[], der für den neuen key bestimmt ist. Der Index wird berechnet mit [c]h & (length-1);[/c], also ein bitweises UND mit h und der Länge des key-Arrays.
So ergibt sich eine relativ zufällige Reihenfolge. Hier die einzelnen Methoden, falls du es selbst noch nachvollziehen willst:

Java:
    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }
Java:
    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
Java:
    static int indexFor(int h, int length) {
        return h & (length-1);
    }
Java:
    void addEntry(int hash, K key, V value, int bucketIndex) {
	Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
        if (size++ >= threshold)
            resize(2 * table.length);
    }
 

eRaaaa

Top Contributor
ähm. ich wollte nur sagen, dass treemap ihre elemente sortiert hält, hashmap nicht.

und nein, es muss nicht alphabetisch sein, du hast ja nicht immer nur strings in der map(bei strings ist die natürliche ordnung so, da hast du recht), bzw hast da auch die möglichkeit, mittels comparator deine eigene sortierung anzugeben

/edit: hier hättest du deine eigene reihenfolge.
Java:
Map<String, String> h = new TreeMap<String, String>(
				new Comparator<String>() {

					@Override
					public int compare(String o1, String o2) {

						//sortiere
					}
				});
		
		h.put("A", "holla@yahoo.de");
		h.put("Cino", "f@hotmail.de");
		h.put("B", "ihallo@gmx.de");
		h.put("Lulu", "lulu@yahoo.de");
		h.put("C", "g@yahoo.de");

		for (Entry<String, String> entry : h.entrySet()) {
			System.out.println(entry.getKey() + "-->" + entry.getValue());
		}
 
Zuletzt bearbeitet:

Prismapanda

Aktives Mitglied
Wenns nicht sortiert sein soll, sondern die Reihenfolge des Einfügens behalten werden soll, sei hier noch auf die LinkedHashMap verwiesen ;-)
 
Status
Nicht offen für weitere Antworten.

Neue Themen


Oben