6

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?

Pentium10
  • 204,586
  • 122
  • 423
  • 502

3 Answers3

10
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.

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • Oh, well done. "The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations." – Michael Mrozek Jun 28 '10 at 22:41
  • Just as I was adding that same quote. =) – ColinD Jun 28 '10 at 22:45
5

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));
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
1

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);
        }
Tell Me How
  • 672
  • 12
  • 16