Alfred’s Computing Weblog

Alfred Java-cored Computing Weblog

Posts Tagged ‘arraylist

Convert ArrayList to Array

leave a comment »

This is a basic Java conversion stuff. I want to convert an ArrayList to a normal Array.
Here is a sample I did and I would like to share it out to anyone who found its useful. 😉

The test driver…

.....
List arrayList_ = new ArrayList();
arrayList_.add("alpha");
arrayList_.add(new String("beta"));
arrayList_.add(new Integer(3));
arrayList_.add(new Float(4.00));
arrayList_.add(new Boolean(true));
.....
Object[] array_ = arrayListToArray(arrayList_);
for (int i=0; i<array_.length; i++) {
    System.out.println("&#91;" + i + "&#93; " + array_&#91;i&#93;);
}
// $>[0] alpha
// $>[1] beta
// $>[2] 3
// $>[3] 4.0
// $>[4] true
.....

The conversion happen here…

private Object[] arrayListToArray(List arrayList) {
    Object[] array = new Object[arrayList.size()];
    arrayList.toArray(array);
    return array;
}
Advertisements

Written by Alfred

December 30, 2008 at 18:11

Posted in Java

Tagged with , , ,