문제

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:

  • 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]);

다른 팁

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]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top