solution1:
The easiest way to do this is to make use of Apache Commons Lang. It has a handy ArrayUtils class that can do what you want. Use the toPrimitive
method with the overload for an array of Integer
s.
List<Integer> myList;
... assign and fill the list
int[] intArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[myList.size()]));
This way you don't reinvent the wheel. Commons Lang has a great many useful things that Java left out. Above, I chose to create an Integer list of the right size. You can also use a 0-length static Integer array and let Java allocate an array of the right size:
static final Integer[] NO_INTS = new Integer[0];
....
int[] intArray2 = ArrayUtils.toPrimitive(myList.toArray(NO_INTS))
solution2: google's guava
ImmutableList<Integer> list = ImmutableList.of(23,0,23,1,-9,234,33);
int [] ef =com.google.common.primitives.Ints.toArray(list);
--------------------------------------------------------------------------------
List<Integer> lst = Lists.newArrayList(); lst.add(Integer.valueOf(12)); lst.add(Integer.valueOf(132)); lst.add(Integer.valueOf(3)); lst.add(Integer.valueOf(2));
int [] ff =com.google.common.primitives.Ints.toArray(lst);
System.out.println("ff:"+com.google.common.primitives.Ints.max(ff));
System.out.println("ff:"+com.google.common.primitives.Ints.min(ff));
List<Integer> tst = Lists.newArrayList();
tst.add(1);
tst.add(-1);
tst.add(45);
Integer[] tt = tst.toArray(new Integer[]{});
//Integer[] tt = tst.toArray(new Integer[tst.size()]);
int [] ef =com.google.common.primitives.Ints.toArray(tst);
System.out.println("ef:"+com.google.common.primitives.Ints.max(ef));
@Test public void testArray(){ ImmutableList<String> params = ImmutableList.of("jgmc", "dlzh","dataToken"); String [] a=params.toArray(new String[params.size()]); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } // jgmc // dlzh // dataToken