I'm trying to use the following line to get an array of the keys from the ConcurrentSkipListMap :
myArray=(String[])myMap.keySet().toArray(new String[myMap.size()]);
But it didn't work, all the items in the result array are the same, why ?
This works as expected:
Map<String, String> myMap = new ConcurrentSkipListMap<>();
myMap.put("a", "b");
myMap.put("b", "c");
String[] myArray= myMap.keySet().toArray(new String[myMap.size()]);
System.out.println(Arrays.toString(myArray));
and outputs:
[a, b]
Note that this is not atomic so if your map is modified between calling size
and toArray
, the following would happen:
myArray
will have a size that is larger than the array you created in new String[myMap.size()]
myArray
will contain null itemsSo it probably makes sense to save a call to size
and avoid a (possibly) unnecessary array creation in this case and simply use:
String[] myArray= myMap.keySet().toArray(new String[0]);