Moley
Moley

Reputation: 123

Array becoming null when List.toArray is used

I'm having an issue where I'm trying to populate an Array with values from a list, then replace the old values with the new ones upon each call of the method. The code below works once, then the next attempt it gives no errors until the new array variable is used , as the array which should have been populated with list data just is full of null values. If anyone has any suggestions much appreciated.

Integer[] stockFF2 =new Integer[ordersBFList.size()]; 
Integer[] ordersFF2 =new Integer[stockBFList.size()];
stockFFList.toArray(stockFF2);
ordersFFList.toArray(ordersFF2);

Upvotes: 4

Views: 1821

Answers (2)

Gene
Gene

Reputation: 47020

The toArray() method makes a fresh array and copies the contents of the list into it.

Try

Integer[] stockFF2 = stockBFList.toArray(); 
Integer[] ordersFF2 = ordersBFList.toArray();

If you want to reuse these arrays (seldom worthwhile), then replace their values with:

stockFF2 = stockBFList.toArray(stockFF2); 
ordersFF2 = ordersBFList.toArray(ordersFF2);

It's unsafe to ignore the return value. If the source Collections get larger, the return value is another fresh array.

Upvotes: 1

MAK
MAK

Reputation: 26586

I think you have got the sizes wrong (orderFF2 and stockFF2 are using the sizes of each other's lists). I suspect one of the arrays is populated properly - one with the larger array - while the other allocates and returns a new array with the elements you want keeping the passed in array as it was because it is too short.

Upvotes: 1

Related Questions