The easiest way to transform collection to array?

后端 未结 8 1755
故里飘歌
故里飘歌 2020-11-27 12:37

Suppose we have a Collection. What is the best (shortest in LoC in current context) way to transform it to Foo[]? Any well-known

相关标签:
8条回答
  • 2020-11-27 13:00

    If you use it more than once or in a loop, you could define a constant

    public static final Foo[] FOO = new Foo[]{};
    

    and do the conversion it like

    Foo[] foos = fooCollection.toArray(FOO);
    

    The toArray method will take the empty array to determine the correct type of the target array and create a new array for you.


    Here's my proposal for the update:

    Collection<Foo> foos = new ArrayList<Foo>();
    Collection<Bar> temp = new ArrayList<Bar>();
    for (Foo foo:foos) 
        temp.add(new Bar(foo));
    Bar[] bars = temp.toArray(new Bar[]{});
    
    0 讨论(0)
  • 2020-11-27 13:15

    Where x is the collection:

    Foo[] foos = x.toArray(new Foo[x.size()]);
    
    0 讨论(0)
提交回复
热议问题