Here I have
class x{
ArrayList<Double> values;
x() {
values= new ArrayList<Double>();
}
//here I want to write a method to convert my arraylis(values) in class(x) into an array to be able to use it in my program. Is there any way to do that. thx for your help.
public double [] getarray(){
}
-
Read this http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28T[]%29noMAD– noMAD2012年04月21日 20:39:48 +00:00Commented Apr 21, 2012 at 20:39
4 Answers 4
You shouldn't really need to turn an ArrayList to an array, but if you do, here's how.
public double [] getArray(){
double[] array = new double[values.size()];
for(int i =0;i<values.size();i++)
{
array[i] = values.get(i) != null ?values.get(i): 0.0;
}
return array;
}
4 Comments
ArrayList.toArray() ;)NullPointerException if any of the elements is null.Your array list have a toArray() method. Try using that one like:
public double [] getarray(){
return values.toArray();
}
With a little help of Apache Commons Lang (see: ArrayUtils.toPrimitive()):
final ArrayList<Double> objList = new ArrayList<Double>();
final Double[] objArray = objList.toArray(new Double[objList.size()]);
final double[] primArray = ArrayUtils.toPrimitive(objArray);
Comments
If the problem is converting it to a primitive double[], and you can use Guava, then double[] Doubles.toArray(Collection<Double>) does the job just fine. (Disclosure: I contribute to Guava.)