How to convert Set to String[]?

前端 未结 7 1895
栀梦
栀梦 2020-11-28 19:12

I need to get a String[] out of a Set, but I don\'t know how to do it. The following fails:

Map myMa         


        
7条回答
  •  忘掉有多难
    2020-11-28 19:33

    Use the Set#toArray(IntFunction) method taking an IntFunction as generator.

    String[] GPXFILES1 = myset.toArray(String[]::new);
    

    If you're not on Java 11 yet, then use the Set#toArray(T[]) method taking a typed array argument of the same size.

    String[] GPXFILES1 = myset.toArray(new String[myset.size()]);
    

    While still not on Java 11, and you can't guarantee that myset is unmodifiable at the moment of conversion to array, then better specify an empty typed array.

    String[] GPXFILES1 = myset.toArray(new String[0]);
    

提交回复
热议问题