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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With