21 Sept 2012

Converting ArrayList into array in java

When working with ArrayList, you will sometimes want to obtain an actual array that contains the contents of the list. As explained earlier, you can do this by calling toArray( ).

// get array
Object ia[] = al.toArray();
int sum = 0;
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}

The output from the program is shown here:

Contents of al: [1, 2, 3, 4]
Sum is: 10

0 comments:

Post a Comment