如何防止 HashSet 更改我从 List 分配的数组顺序?

How to prevent HashSet to change my array order that i assign from List?

我想要实现的是我的 Set 与我的 List 具有相同的顺序,当我将值从 List 分配给 Set 时,它正在改变。这是我所做的:

// in here my array still showing same as my submited front end
List<ShipmentAddressGroupingDtDto> submitedShipmentAddressGroupingDtDto = shipmentAddressGroupingDto.getShipmentAddressGroupingDtDto();

//in here my array start changing, it's not the same order again as my object above
        Set<ShipmentAddressGroupingDtDto> setShipmentAddressGroupingDtDto = new HashSet(submitedShipmentAddressGroupingDtDto);
        List<ShipmentAddressGroupingDtDto> shipmentAddressGroupingDtDto = new ArrayList<ShipmentAddressGroupingDtDto>(setShipmentAddressGroupingDtDto);

这是我的 submitedShipmentAddressGroupingDtDto 值:

      [
        "id": 0,
        "address": "Jl. Imam Bonjol",
        "isActive": true,
        "partnerShipmentId": 1
      ],
      [
        "id": 0,
        "address": "Jl. Imam Bonjol",
        "isActive": true,
        "partnerShipmentId": 2
      ],
      [
        "id": 0,
        "address": "Jl. Imam Bonjol",
        "isActive": true,
        "partnerShipmentId": 4
      ],
      [
        "id": 0,
        "address": "Jl. Imam Bonjolx",
        "isActive": true,
        "partnerShipmentId": 7
      ]

我在调试模式下看到的,在我的 setShipmentAddressGroupingDtDto 中是这样的:

      [
        "id": 0,
        "address": "Jl. Imam Bonjol",
        "isActive": true,
        "partnerShipmentId": 2
      ],
      [
        "id": 0,
        "address": "Jl. Imam Bonjolx",
        "isActive": true,
        "partnerShipmentId": 7
      ],
      [
        "id": 0,
        "address": "Jl. Imam Bonjol",
        "isActive": true,
        "partnerShipmentId": 1
      ],
      [
        "id": 0,
        "address": "Jl. Imam Bonjol",
        "isActive": true,
        "partnerShipmentId": 4
      ]

如何防止 Set 对我的列表进行排序?或者,如果我无法阻止,我该如何将其排序为我提交的值?

您可以使用 LinkedHashSet 来维护您放入其中的元素的顺序。