3

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.

3
  • 1
    You have to iterate through every elements, and convert each one. Difficult to do better and faster ... Commented Dec 6, 2015 at 21:19
  • @guillaumegirod-vitouchkina I don't understand what you mean by iterate through every element. Is that what the answer below is doing by Viacheslav Vedenin? Commented Dec 6, 2015 at 21:21
  • Yes, your String[] stringArray = oneList.toArray(new String[oneList.size()]); can be avoided, as in the solution given. Commented Dec 6, 2015 at 21:25

1 Answer 1

4

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}

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

4 Comments

Why is a for each loop better?
It's more readable in the most case, so other programmers can understand your code quite easy
I just don't see the need when you replace it with a for (int i ..., then do String value = oneList.get(i) on the first line. While it is more readable, it is not as concise when you have to remember to manually assign and increment i in 2 different lines.
Don't catch "Exception". Catch NumberFormatException instead, you don't want to catch everything that could possibly go wrong.

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.