1

I need to convert an ArrayList to a String array which is declared as final,

I ended up with this:

        //new array
        String[] arrTextRow=new String[customListTxt.size()];
        customListTxt.toArray(arrTextRow);
        //new final array 
        final String[] arrTextRow2=arrTextRow;

it's working, but just wondering if there is a more elegant way to achieve this, such as:

        final String[] arrTextRow =new String[]{
            for(String zz : customListTxt){
                //dosomethinghere
            }
        };
1
  • 2
    Why not just declare arrTextRow final? Commented May 22, 2019 at 8:27

4 Answers 4

1

I prefer the one liner:

final String[] arrTextRow2=customListTxt.toArray(new String[0]);

The new String[0] is not that expensive, but you can always make it a constant.

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

1 Comment

Thanks! also previous solutions are fine, but this is the one I prefer
0

You can declare the first Array arrTextRow final too.

//Convert to string array
final String[] arrTextRow = customListTxt.toArray(new String[customListTxt.size()]);

Comments

0

You can use list.toArray()

final String[] array = customListTxt.toArray(new String[customListTxt.size()]);

Comments

0

I think there is no way more elegant than toArray(). Also, you can define arrTextRow as final.

final String[] arrTextRow = new String[customListTxt.size()];

The point is, final doesn't make array element immutable, but the array reference itself, i.e., after defining the array as final, you cannot change the arrTextRow, but still can change the individual elements of it.

See here for example

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.