HashMap should be unsorted but still sorted according to key

In accordance with this:

HashMapin Javashould be unsorted, but it is sorted relatively Key.

I experienced this as a problem because I need data with an inserted order. So, I used LinkedHashMap. But still I am confused why I HashMapsorted it.

Can anyone explain this?

I made a simple example to view sorting.

public static void main(String[] args) {

        HashMap<Integer, String> newHashMap = new HashMap<Integer, String>();
        newHashMap.put(2, "First");
        newHashMap.put(0, "Second");
        newHashMap.put(3, "Third");
        newHashMap.put(1, "Fourth");

        Iterator<Entry<Integer, String>> iterator = newHashMap.entrySet()
                .iterator();
        while (iterator.hasNext()) {

            Map.Entry<Integer, String> entry = iterator.next();
            System.out.println("Key: " + entry.getKey());
            System.out.println("Value: " + entry.getValue());
            iterator.remove();
        }

    }

Result:

Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third

Edit:

50 , Random Java, . .

:

...
Key: 36
Value: random
Key: 43
Value: random
Key: 47
Value: random
Key: 44
Value: random
Key: 45
Value: random
...
+4
9

( , , ).

newHashMap.put(-5, "Fifth");

.

Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
Key: -5
Value: Fifth

javadoc :

; , , .

+5

. , , , , .

:

import java.util.Map;
import java.util.HashMap;

class MapTest {

    public static void main(String[] args){
        int count = Integer.parseInt(args[0]);
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < count; i++) map.put(i, i);
        System.out.println(map);
    }

}

java MapTest 20 ( ):

{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10, 11=11, 12=12, 13=13, 
14=14, 15=15, 17=17, 16=16, 19=19, 18=18}

HashMap, Integer, ( 0).

+1

! , , , .

- int int, , , , .

, , . ,

100,200,300,100001, 100002, 10003, 999123456, 888777666,....

+1

, . , , : HashMap "". . , .

[0] -> [ Bin0: ... ]
[1] -> [ Bin1: ... ]
[2] -> [ Bin2: ... ]
[3] -> [ Bin3: ... ] 

HashMap, "Bin", , - - hashCode() . , hashCode 2, Bin 2. "" , Bin (index% arraySize) - , hashCode 5, Bin 1.

HashMap 10, Integer 0 9 . (- - , ).

(: - , )

+1

, ( ), , HashMap . LOOK :

1 - Integer : HashMap hashCode() Object Java , Entry ( HashMap). , - Integer .

2 - HashMap , , ( 16). , 0 16 ( ), , . HashMap ,

int index = newKey.hashCode() % this.capacity;

HashMap , - ( , , ), , Integer , .

Btw, , , , . , .

+1

HashMap. , , . .

0

.

Hashmap - - .

, .

0

Mine - , , hashCode . Integer ( Integer), , : Integer.valueOf(1) . , , . , , Integer HashMap, .

: Integer " - , int, Integer". (JavaDoc). , , .

0

, Java, !:)

put(), - - , . [put() ]

hash() , -, , [ Google , .

, . .

0

Source: https://habr.com/ru/post/1526708/


All Articles