0

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 ?

4

2 回答 2

1

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:

  • if the new map is smaller, myArray will have a size that is larger than the array you created in new String[myMap.size()]
  • if the new map is larger, myArray will contain null items

So 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]);
于 2013-07-24T17:20:23.130 回答
1

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]

于 2013-07-24T17:22:30.180 回答