4

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);
5
  • From this code, I can not figure out what you are hoping to happen Commented Dec 16, 2015 at 1:05
  • 1
    Add doe which produces the exception and post the stack trace and tell us at what line it happens. Commented Dec 16, 2015 at 1:05
  • 4
    +, it seems like you should switch sizes. Commented Dec 16, 2015 at 1:05
  • 1
    @sparta Thanks! that at solved one issue but the null one is still there though Commented Dec 16, 2015 at 1:39
  • null speaks for itself. You tripped somewhere in your code. Keep digging. Commented Dec 16, 2015 at 1:42

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Actually. toArray works in both modes, either taking an array as an argument, filling it as well as returning it. BUT the input array must match the list size, which is the problem in the OP example, where the two lists are swapped. toArray() without an argument returns an Object array.
"It's unsafe to ignore the return value." - +10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.