I am seeing a unique situation where my keyset
and key
of a LinkedHashSet
are containing different data types as shown below
As you can see that the key
is a String
and the keyset
is a long
.
Following code is failing because of that:
modifiedRowKeys.toArray(new Long[modifiedRowKeys.size()]);
I get ArrayStoreException
for String
values.
I was able to replicate this from Angular application where i am sending a Map<Long, Map<String,Object>>
to my Spring server which contains the data as shared in the pic.
Edit 1:
Please see following strange behavior in eclipse:
Could it be an issue with Jackson Mapper which we are using for conversion of objects ?
Edit 2:
The following code fails with ClassCastException
saying
String cannot be cast to Long
Set<Long> modifiedRowKeys = modifiedRowMap.keySet();
Long[] periodDateArray = new Long[modifiedRowKeys.size()];
int count = 0;
Iterator<Long> keyIterator = modifiedRowKeys.iterator();
while(keyIterator.hasNext()){
Long key = keyIterator.next();
System.out.println("key instanceof Long : " + (key instanceof Long));
periodDateArray[count++] = Long.valueOf(key);
}
This seems pretty straight forward logic !
Edit 3:
I have recreated the problem as follows:
public static void main(String[] args) {
CollectionsToArray collectionsToArray = new CollectionsToArray();
Map<String, Map<String, Object>> mapOfNumbers = collectionsToArray.prepareStrangeNumbersSetFromMapOfMap();
Object obj = mapOfNumbers;
collectionsToArray.convertMapToKeySetToArray(obj);
}
private Map<String, Map<String, Object>> prepareStrangeNumbersSetFromMapOfMap() {
Map<String, Map<String, Object>> longNumberMap = new LinkedHashMap<>();
Map<String, Object> stringValueMap = new HashMap<>();
stringValueMap.put("Adams", "Adithya");
stringValueMap.put("Edge", 80);
longNumberMap.put("1488376800000", stringValueMap);
return longNumberMap;
}
private void convertMapToKeySetToArray(Object obj) {
Map<Long, Map<String, Object>> mapOfNumbers = (Map<Long, Map<String, Object>>) obj;
Set<Long> stringNumbers = mapOfNumbers.keySet();
convertLongKeySetToArray(stringNumbers);
}
private void convertLongKeySetToArray(Set<Long> stringNumbers) {
Long[] stringNumbersArray = stringNumbers.toArray(new Long[0]);
Arrays.sort(stringNumbersArray);
System.out.println(stringNumbersArray);
}