【发布时间】:2015-09-01 11:36:22
【问题描述】:
这是我的代码。我仅作为示例实现 List。
public class Main {
public static Integer[] toObject(int[] array) {
Integer[] result = new Integer[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Integer(array[i]);
}
return result;
}
public static Double[] toObject(double[] array) {
Double[] result = new Double[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Double(array[i]);
}
return result;
}
public static Long[] toObject(long[] array) {
Long[] result = new Long[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Long(array[i]);
}
return result;
}
public static Boolean[] toObject(boolean[] array) {
Boolean[] result = new Boolean[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Boolean(array[i]);
}
return result;
}
public static <T> void fromArrayToCollection(T[] array, Collection<T> c) {
for (T o : array) {
c.add(o);
}
}
public static void main(String[] args) {
int [] i = new int[2];
i[0] = 1;
i[1] = 1;
Integer [] ii = toObject(i);
List<Integer> ic = new ArrayList<Integer>();
fromArrayToCollection(ii, ic);
ic.add(3);
ic.add(4);
System.out.println(ic);
long [] l = new long[2];
l[0] = 1L;
l[1] = 2L;
Long [] ll = toObject(l);
List<Long> lc = new ArrayList<Long>();
fromArrayToCollection(ll, lc);
lc.add(3L);
System.out.println(lc);
double [] d = new double[2];
d[0] = 1.0;
d[1] = 2.0;
Double [] dd = toObject(d);
List<Double> dc = new ArrayList<Double>();
fromArrayToCollection(dd, dc);
dc.add(3.0);
System.out.println(dc);
boolean [] b = new boolean[2];
b[0] = true;
b[1] = false;
Boolean [] bb = toObject(b);
List<Boolean> bc = new ArrayList<Boolean>();
fromArrayToCollection(bb, bc);
bc.add(true);
System.out.println(bc);
String [] s = new String[2];
s[0] = "One";
s[1] = "Two";
List<String> sc = new ArrayList<String>();
fromArrayToCollection(s, sc);
sc.add("Three");
System.out.println(sc);
}
}
Java 不能为原始数据类型提供泛型。为此,我编写了在 Object 中的原始类型之间进行转换的方法。我有四种从原始转换为对象的方法。如何在单一方法中实现它?我需要以单一方法实现从原始到对象的转换。谢谢
【问题讨论】:
-
你不应该使用
new Integer、new Boolean等。通常这只是浪费内存。使用Integer.valueOf、Boolean.valueOf或隐式自动装箱(仅result[i] = array[i])。 -
顺便说一下,
valueOf()通常更好,因为它不是每次都创建一个新对象,而是对某些值进行特殊处理。
标签: java object type-conversion