我写的这个要点很好地解决了这个问题。
遵循siegi关于Atreys答案的建议,我编写了一个构造函数,该构造函数查找“最近的共同祖先”(NCA)类并使用该类创建数组。如果检查空值,并且提供的Collection的长度为0或所有空值,则默认类型为Object。它完全忽略了接口。
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.lang.reflect.Array;
import java.util.Iterator;
public class FDatum<T> {
public T[] coordinates;
public transient HashSet<Class> classes = new HashSet<Class>(5);
public FDatum (Collection<T> coordinates) {
for (T t : coordinates) this.classes.add(t.getClass());
List<Class> classes = new ArrayList<Class>(this.classes);
Class NCA = Object.class;
for (int ii = 0; ii < classes.size(); ++ii) {
Class c = classes.get(ii);
if (c == null) continue;
NCA = c; break;
}
if (!NCA.equals(Object.class)) {
for (int ii = 0; ii < classes.size(); ++ii) {
Class c = classes.get(ii);
if (c == null) continue;
System.out.println(c);
while (!NCA.isAssignableFrom(c))
NCA = NCA.getSuperclass();
}
}
System.out.println("NCA: " + NCA);
T[] coords = (T[]) Array.newInstance(NCA, coordinates.size());
ArrayList<T> coordslist = new ArrayList<T>(coordinates);
for (int ii = 0; ii < coordslist.size(); ++ii)
coords[ii] = coordslist.get(ii);
this.coordinates = coords;
}
public FDatum (T[] coordinates) {
this.coordinates = coordinates;
}
}
以下是在jshell中使用它的一些示例(为简洁起见,删除了“未经检查的”类警告):
jshell> FDatum d = new FDatum(new ArrayList(Arrays.asList((double)1, (Double)3.3)))
class java.lang.Double
NCA: class java.lang.Double
d ==> com.nibrt.fractal.FDatum@9660f4e
jshell> d.coordinates
$12 ==> Double[2] { 1.0, 3.3 }
jshell> d = new FDatum(new ArrayList(Arrays.asList((double)1, (Double)3.3, (byte)7)))
class java.lang.Byte
class java.lang.Double
NCA: class java.lang.Number
d ==> com.nibrt.fractal.FDatum@6c49835d
jshell> d.coordinates
$14 ==> Number[3] { 1.0, 3.3, 7 }
jshell> d = new FDatum(new ArrayList(Arrays.asList((double)1, (Double)3.3, (byte)7, "foo")))
class java.lang.Byte
class java.lang.Double
class java.lang.String
NCA: class java.lang.Object
d ==> com.nibrt.fractal.FDatum@67205a84
jshell> d.coordinates
$16 ==> Object[4] { 1.0, 3.3, 7, "foo" }
List.toArray
呢?