java.lang.UnsupportedOperationException ImmutableList.remove 当我没有使用 ImmutableList 时

java.lang.UnsupportedOperationException ImmutableList.remove when i didn't use ImmutableList

我有这个代码

    final List<String> connectedIds = getConnectedDevices();
    final List<Device> allDbDevicesAsList = getAllDbDevicesAsList();

    List<Device> connectedDevices = new ArrayList<>();
    for (int i = 0; i < allDbDevicesAsList.size(); i++) {
        int size = connectedIds.size();
        for (int j = 0; j < size; j++) {
            final Device currentDevice = allDbDevicesAsList.get(i);
            if(currentDevice.uuid == connectedIds.get(j))
            {
                connectedDevices.add(currentDevice);
                connectedIds.remove(j);
                break;
            }
        }
    }

我得到了这个异常,即使我不使用 ImmutableList

我深入研究了 getConnectedDevices()

的所有方法调用
java.lang.UnsupportedOperationException
    at com.google.common.collect.ImmutableList.remove(ImmutableList.java:479)
    at com.waze.automation.client.services.web.lib.devices.DevicesServiceLocal.getDevices(DevicesServiceLocal.java:66)
    at com.waze.mobileautomation.devices.DevicesServiceLocalTest.testGetAvailableDevices_returnsOnly(DevicesServiceLocalTest.java:194)

使用此代码将获得相同的交集逻辑,但效率较低。

    List<Device> connectedDevices = allDbDevicesAsList.stream()
            .filter(item -> connectedIds.contains(item.uuid))
            .collect(Collectors.toList());

你会如何重写交集代码?

为什么我还是会收到这个错误?

您可以将设备 ID 列表从 getConnectedDevices() 方法传递到新的 ArrayList:

 final List<String> connectedIds = new ArrayList<>(getConnectedDevices());

这会将所有值从 ImmutableList 复制到一个 ArrayList 中,您可以从中删除项目。

您提供的使用流的示例看起来更加简洁易懂。除非它具有不可接受的已确认性能影响,否则它看起来是最好的方法。

来自 java 文档,它说。它不保证可变性。

public static <T> Collector<T,?,List<T>> toList()

Returns 一个收集器,将输入的元素累积到一个新的列表中。不保证返回列表的类型、可变性、可序列化性或线程安全性;如果需要对返回的列表进行更多控制,请使用 toCollection(Supplier)。 类型参数: T - 输入元素的类型 Returns: 一个 Collector,它将所有输入元素按遇到的顺序收集到一个列表中。

您可以尝试打印 getConnectedDevices() 返回的列表类型。

复制连接的设备 ID List。此副本将是可变的。

List<String> connectedIds = new ArrayList<String>(getConnectedDevices());
List<Device> allDbDevicesAsList = getAllDbDevicesAsList();

List<Device> connectedDevices = new ArrayList<Device>();

for (int i = 0; i < allDbDevicesAsList.size(); i++) {
    Device currentDevice = allDbDevicesAsList.get(i);
    boolean removed = connectedIds.remove(currentDevice.uuid);
    if (removed) {
        connectedDevices.add(currentDevice);
    }
}

PS:id的集合应该是Set而不是列表。例如

Set<String> connectedIds = new HashSet<String>(getConnectedDevices());