This is my Code. I implement List only for example.
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 can't have generics for primitive data types. For that i write methods that convert between primitive types in Object. I have four method that converted from primitive to object. How it could be implemented in a single method? I need that convert to object from primitive was implemented in single method. Thanks