有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在通过REST Api发送之前,java是否会操纵map中键的顺序?

我有一个LinkedHashMap,它有键(字符串)和值(某个对象的列表)对。在返回语句之前,键的顺序是正确的。在UI端收到它后,键的顺序似乎改变了

java在这里扮演什么角色?如果是,如何纠正?我想要从数据库返回的UI上的相同序列


共 (1) 个答案

  1. # 1 楼答案

    记录LinkedHashMap

    Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

    Java中的LinkedHashMap将保持插入顺序。如果从有序列表中读取键值对,并以相同的顺序将其插入到LinkedHashMap中,则该排列将被保留

    这就是说,如果您是从JSON中阅读这篇文章,那么对的排序应该被认为是非排序的

    来自JSON规范RFC 8259

    An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

    此外:

    JSON parsing libraries have been observed to differ as to whether or not they make the ordering of object members visible to calling software. Implementations whose behavior does not depend on member ordering will be interoperable in the sense that they will not be affected by these differences.

    如果您需要解决方法,那么您可以按照clayton.carmo提供的答案进行操作。这种解决方法的工作原理是将JSON对象表单转换为键值对象的JSON数组。这保证维持秩序。从RFC文档中:

    An array is an ordered sequence of zero or more values.