【问题标题】:Convert list to set by ImmutableSet.copyOf() and new HashSet<>(list);将列表转换为由 ImmutableSet.copyOf() 和 new HashSet<>(list) 设置的;
【发布时间】:2015-09-10 09:16:00
【问题描述】:

早安,

我有一个包含一些数据的集合:

Set< AItem > aItems = aItem
                    .getItems( );

因为我想做一些排序,所以我先转换成list,排序后,再转回set:

List< AItem > tempoAccounts = new ArrayList(aItems);

Collections.sort(tempoAccounts, new Comparator() {
                public int compare(Object arg0, Object arg1) {
                    // sorting logic here
                }
            });

// convert from list back to set
aItems = ImmutableSet.copyOf(tempoAccounts);

这给了我一个正确的结果,我的所有数据都相应地排序。

但是,如果我想在aItems 中添加更多项目:

AItem aai = new AItem();
            aai.setAId( (long) 2222 );
            aai.setLimit( BigDecimal.ZERO );

那我就打:

Exception created : [java.lang.UnsupportedOperationException
    at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:91)

所以我改了

aItems = ImmutableSet.copyOf(tempoAccounts);

aItems = new HashSet<AItem>(tempoAccounts);

如果我在这个集合中添加新项目,这不会给我UnsupportedOperationException。但是我的排序不见了,Set 没有正确排序。

有什么想法可以对我的 Set 进行排序,然后可以毫无例外地在里面添加更多项目?

请多多指教。

【问题讨论】:

  • 你为什么不直接使用TreeSet

标签: java list sorting set unsupportedoperation


【解决方案1】:

HashSet 应被视为无序集。如果你想要一个排序集,只需使用TreeSet

Set<AItem> sortedItems = new TreeSet<>(new Comparator<AItem>() { ... });
sortedItems.addAll(aItems);

(不要使用 Comparator 的原始类型,顺便说一句...尽量避免使用原始类型。)

无需创建列表,无需创建不可变集合...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 2023-01-14
    • 1970-01-01
    相关资源
    最近更新 更多