简体   繁体   English

NetBeans更改HashMap中的键顺序

[英]NetBeans changing order of keys in HashMap

It appears that NetBeans tends to modify the order of key-value pairs when placing them into a HashMap as compared to the HashMap objects created by calling javac.exe and java.exe directly. 与直接调用javac.exejava.exe创建的HashMap对象相比,NetBeans在将键-值对放入HashMap时倾向于修改其顺序。

Consider the following class definitions ( package and import declarations omitted): 考虑以下类定义(省略了packageimport声明):

class Coder {

    enum Gender { FEMALE, MALE  }
    String name;
    Gender gender;

    Coder(String name, Gender gender) {
        this.name = name;
        this.gender = gender;
    }

    String getName() { return name; }
    Gender getGender() { return gender; }
}

class Test{
    public static void main(String[] args) {
        List<Coder> list = Arrays.asList(
                new Coder("Alice", Coder.Gender.FEMALE),
                new Coder("Chuck", Coder.Gender.MALE),
                new Coder("Bob", Coder.Gender.MALE));
        Map<Coder.Gender, List<String>> classification = list.stream()
                        .collect(Collectors.groupingBy(Coder::getGender,
                                 Collectors.mapping(Coder::getName, Collectors.toList())));
        System.out.println(classification);

        // Getting metainfo:
        System.out.println("Actual map's type at runtime is " +
                           classification.getClass().getSimpleName());
        System.out.println("OS: " + System.getProperty("os.name") +
                           ", ver." + System.getProperty("os.version"));
        System.out.println("Java ver.: " + System.getProperty("java.version"));

        // Serializing:
        String filename = "classification_cmd.ser";
        // String filename = "classification_NetBeans.ser";  // toggle commenting-out as needed
        File file = new File(filename);
        try (
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream outs = new ObjectOutputStream(fos)
        )
        { outs.writeObject(classification);
        } catch (IOException ioe) { ioe.printStackTrace(); };
    }
}

Compiling and running the above code directly from command line in Windows (Java ver.1.8.0_066) produced this: 直接在Windows(Java ver.1.8.0_066)的命令行中编译并运行上述代码会产生以下结果:

{MALE=[Chuck, Bob], {FEMALE=[Alice]}

Under Linux from the CLI on my Raspberry Pi (Java ver.1.80_065) and via ideone.com (Java ver.1.8.0_112) results were essentially the same: first MALE group, then FEMALE one. 在Linux下,我的Raspberry Pi上的CLI(Java版本1.80_065)和ideone.com (Java版本1.8.0_112)上的结果基本相同:首先是MALE组,然后是FEMALE组。 However, in NetBeans 8.1 under Windows (Java ver.1.8.0_066) the output was reversed: 但是,在Windows(Java版本1.8.0_066)下的NetBeans 8.1中,输出是相反的:

{FEMALE=[Alice], MALE=[Chuck, Bob]}

In all cases the actual type of the map in question was HashMap . 在所有情况下,相关地图的实际类型均为HashMap Serializing the map to disk and peeking inside confirmed that the objects were indeed different in terms of the order of key-value pairs: 将映射序列化到磁盘并在内部进行偷看确认,这些对象确实在键值对的顺序方面有所不同:

- from command line: -从命令行: 在此处输入图片说明

- from inside NetBeans: -从NetBeans内部: 在此处输入图片说明

Hence my questions: 因此,我的问题是:

  • Why does it happen, and 为什么会发生,以及
  • What should be done (I mean, apart from forced sorting such as employing a TreeMap built around a custom Comparator , etc.) to ensure that results will be exactly the same regardless of how we compile and run our programs, from command line or from within NetBeans? 应该做什么(我的意思是,除了强制排序(例如使用围绕自定义Comparator构建的TreeMap等)之外),以确保无论从命令行还是从命令行编译和运行程序的方式,结果都将完全相同在NetBeans中?

There is no guarantee that a general Map implementation retains any order of the added elements. 无法保证常规Map实现会保留添加元素的任何顺序。

If you do care about that order, you do need to use a NavigableMap like TreeMap which keeps the keys ordered. 如果您确实关心该顺序,则确实需要使用像TreeMap这样的NavigableMap来保持键的顺序。 You don't usually need to provide a Comparator, it uses they key type's natural order if none is given. 通常不需要提供Comparator,如果没有给出,则使用它们的键类型自然顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM