Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ArrayList<String> to int[]

In my code I am converting an ArrayList<String> to int[] by using this code.

ArrayList<String> oneList = new ArrayList<String>();

oneList.add("7");
oneList.add("525");
oneList.add("85");
oneList.add("365");
oneList.add("78");
oneList.add("1");

String[] stringArray = oneList.toArray(new String[oneList.size()]);

int[] arrayOfValues = new int[oneList.size()];  

for(int i = 0;i < stringArray.length;i++)
{   
    try
    {
        arrayOfValues[i] = Integer.parseInt(stringArray[i]);
    }
    catch(Exception e)
    {
        System.out.println("Not an integer value");
    }
}

Is this the most efficient way of completing this or should I be going about it differently? I would also be interested in any alternatives to the way I did it if you have one.

like image 615
Dan Avatar asked Jun 24 '26 03:06

Dan


1 Answers

Better use following code:

ArrayList<String> oneList = new ArrayList<String>();

oneList.add("7");
oneList.add("525");
oneList.add("85");
oneList.add("365");
oneList.add("78");
oneList.add("1");

int[] arrayOfValues = new int[oneList.size()];  
int i = 0;
for(String value: oneList)
{   
    try
    {
        arrayOfValues[i] = Integer.parseInt(value);
        i++;
    }
    catch(Exception e)
    {
        System.out.println("Not an integer value");
    }
}

In your code:

1) You create a String[] array but that not need at all.

2) Using a for each loop is better than for(int i..)

3) If you have exception, arrayOfValues has empty element, for example if oneList = {"1", "aaa", "2"} then arrayOfValues = {1, 0, 2}. However it is sometimes better if arrayOfValues = {1, 2}

like image 115
Slava Vedenin Avatar answered Jun 25 '26 21:06

Slava Vedenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!