How can I parse a set of numeric strings into a generic array? My whole problem can be reduced to the following:
static <T extends Number> T[] parseBulk(String bulk, Class<T> type) throws ParseException {
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setParseIntegerOnly(false);
String[] elements = bulk.split(";");
T[] result = (T[])Array.newInstance(type, elements.length);
for (int i= 0; i< elements.length; i++)
result[i] = (T)numberFormat.parse(itemElements[i]); // here it crashes
// result[i] = type.cast(numberFormat.parseObject(itemElements[i])); // does not work either
return result;
}
...
Double[] shouldBeDoubles = parseBulk("15.5;10", Double.class);
Looks like Number determines resulting type by content of the String given, which yields a Double for "15.5" and a Long for "10".
Then it happily crashes trying to convert Long to T, which is Double.
Thank you,
Update : added numberFormat to the source code. Excuse me :)
NumberFormat.parse(String source)
returns a Number
. The runtime type of the returned instance can be any sub-class of Number
, so if it returns a Long
, you can't cast it to Double
, as you learned.
If you want to force the numeric type that the String
s will be converted to, you can pass a parser Function
to the method:
static <T extends Number> T[] parseBulk(String bulk, Class<T> type, Function<String,T> parser) {
String[] elements = bulk.split(";");
T[] result = (T[])Array.newInstance(type, elements.length);
for (int i= 0; i< elements.length; i++) {
result[i] = parser.apply(elements[i]);
}
return result;
}
And call it, for example, with:
Double[] shouldBeDoubles = parseBulk("15.5;10", Double.class,Double::valueOf);
This will output:
[15.5, 10.0]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.