You should create a general method for converting from one type to another. Here is a simple interface for this:
public interface XFormer<T,U> { public T xform(U item); }
Then you would use this in a generic conversion method:
public static <T, U> List<T> xForm(List<U> original, XFormer<T, U> strategy) { List<U> ret = new ArrayList<U>(original.size()); for (U item: original) { ret.add(strategy.xform(item)); } return ret; }
One of them might look like this:
List<String> original; List<Long> xFormed = xForm(original, new XFormer<Long, String>() { public Long xForm(String s) { return Long.parseLong(s); } });
I use the same strategy in one of my open source projects. Take a look at JodeList on line 166 for an example. In my case, this is a little simplified, because it only converts from Jode to any type, but it needs to be extended to convert between any types.
source share