简体   繁体   English

如何从数组添加到SortedSet项目?

[英]How to add to SortedSet items from an Array?

I have a SortedSet defined this way: 我有这样定义的SortedSet:

SortedSet<RatedMessage> messageCollection = new TreeSet<RatedMessage>(new Comp());

and I have an array of RatedMessage[] 并且我有一个RatingMessage []数组

I had to use the array as the set misses the serialization feature, now I need to construct it back. 我必须使用数组,因为集合缺少序列化功能,现在我需要重新构造它。

Is there a quick way to add all the items from the array to the set again? 有没有一种快速的方法可以将数组中的所有项目再次添加到集合中?

Collections.addAll(messageCollection, array);

Functionally identical to Michael's answer, but as the javadoc says: 功能上与Michael的答案相同,但正如javadoc所说:

Adds all of the specified elements to the specified collection. 将所有指定的元素添加到指定的集合中。 Elements to be added may be specified individually or as an array. 要添加的元素可以单独指定或作为数组指定。 The behavior of this convenience method is identical to that c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations. 此便捷方法的行为与c.addAll(Arrays.asList(elements))相同,但是在大多数实现下,此方法的运行速度可能明显更快。

Set has an addAll method, but it only takes a collection, so you'll need to convert the array first: Set有一个addAll方法,但是它只需要一个集合,因此您需要先转换数组:

RatedMessage[] arr;
messageCollection.addAll(Arrays.asList(arr));

You can add RatedMessage[] array into SortedSet using Arrays.asList with TreeSet 您可以使用带有TreeSet的 Arrays.asListRatingMessage []数组添加到SortedSet中

String RatedMessage[]={"1","2","3","1","4","3"};
SortedSet lst= new TreeSet(Arrays.asList(RatedMessage));
Iterator it = lst.iterator();
        while(it.hasNext())
        {
            Object ob= it.next();
            System.out.println(ob);
        }

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

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