0

I am getting the following error when executing the code below...

I am trying to convert the list of Object arrays to a BigDecimal array using the toArray() method of the List collection..

When I simply give fileFormatObj.toArray() it is working fine, but when I give like in the code below I am getting the error....

public static void main(String[] args) 
{
    List<BigDecimal> objList = new ArrayList<BigDecimal>();
    List<Object[]> fileFormatObj = new ArrayList<Object[]>();
    final Object[] array1 = new Object[1];
    array1[0] = new BigDecimal(BigInteger.ONE);
    fileFormatObj.add(array1);
    if (fileFormatObj != null) 
    {
        //Error here java.lang.System.arraycopy    
        final BigDecimal[] arr = fileFormatObj
            .toArray(new BigDecimal[fileFormatObj.size()]);

        objList.addAll(Arrays.asList(arr));
        for (final BigDecimal object : arr) {
            System.out.println("TEST-->" + object.intValue());
        }
    }
}

1 Answer 1

5

The problem is that the element in fileFormatObj is an Object[], not a BigDecimal. Therefore you can't convert fileFormatObj to a BigDecimal[]. You can't even convert it to a BigDecimal[][] (as an Object[] isn't a BigDecimal[]) but at the moment you're trying to store an array reference in a BigDecimal[]...

It's not clear why you're trying to do it like this, but that's simply not going to work. If you edit your question to explain why you're trying to do this - what the bigger picture is - we can help you more.

If you absolutely have to convert a List<Object[]> to a BigDecimal[] and you want to take the first element of each array, you could use something like:

BigDecimal[] arr = new BigDecimal[fileFormatObj.size()];
for (int i = 0; i < arr.length; i++) {
    Object[] fileFormatArray = fileFormatObj.get(i);
    Object firstElement = fileFormatArray[0];
    arr[i] = (BigDecimal) firstElement;
}

You can do the whole for loop body in a single statement of course - I only split it up here to make it clear exactly where the cast to BigDecimal needs to happen.

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

Comments

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.