문제

I have a SortedSet defined this way:

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

and I have an array of RatedMessage[]

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:

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.

다른 팁

Set has an addAll method, but it only takes a collection, so you'll need to convert the array first:

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

You can add RatedMessage[] array into SortedSet using Arrays.asList with TreeSet

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top