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 ?
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]);
You can try this:
ConcurrentSkipListMap myMap = new ConcurrentSkipListMap();
myMap.put("3", "A");
myMap.put("2", "B");
myMap.put("1", "C");
myMap.put("5", "D");
myMap.put("4", "E");
Object[] myArray = myMap.keySet().toArray();
System.out.println(Arrays.toString(myArray));
The result will be:
[1, 2, 3, 4, 5]