HashMap 应该是未排序的,但仍然根据 key 排序

HashMap should be unsorted but still sorts according to key(HashMap 应该是未排序的,但仍然根据 key 排序)
本文介绍了HashMap 应该是未排序的,但仍然根据 key 排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

根据这些:

  1. http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
  2. HashMap、LinkedHashMap和TreeMap的区别
  3. java初学者:如何在hashmaps中对key进行排序?

Java 中的 HashMap 应该是未排序的,但它正在根据 Key 进行排序.

The HashMap in Java should be unsorted but it is being sorted with respect to Key.

我遇到了这个问题,因为我需要插入订单数据.所以,我使用 LinkedHashMap 代替.但是我仍然很困惑为什么 HashMap 对其进行排序.

I experienced this as a problem because I needed inserted-order data. So, I used LinkedHashMap instead. But still I am confused why the HashMap sorted it.

谁能解释一下?

我做了一个简单的例子来查看排序.

I did a simple example to view the sort.

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();
        }

    }

结果:

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

我尝试使用 JavaRandom 插入 50 个随机数,但发现一些数据未排序.但是,它仍然能够对大多数整数进行排序.

I tried to insert 50 random numbers using Random of Java and I found some data unsorted. But, it still manages to sort most of the integers.

随机结果:

...
Key: 36
Value: random
Key: 43
Value: random
Key: 47
Value: random
Key: 44
Value: random
Key: 45
Value: random
...

推荐答案

这是巧合(不是真的,而是与哈希算法有关).

It's a coincidence (not really, rather it has to do with the hashing algorithm).

尝试添加

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 具体说

The javadoc specifically says

这个类不保证地图的顺序;特别是,它不保证订单会随着时间的推移保持不变.

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

这篇关于HashMap 应该是未排序的,但仍然根据 key 排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)