I wanna make an apps that need to convert ArrayList<String>[]
to ArrayList<Integer>[]
, I also used this :
ArrayList<String>[] strArrayList;
int ArrayRes = (int) strArrayList[];
but this code get me an error , anybody can help me ?
Any suggestion would be appreciate
Define a method which will convert all String value of arraylist into integer.
private ArrayList<Integer> getIntegerArray(ArrayList<String> stringArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for(String stringValue : stringArray) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(stringValue));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + stringValue + " can not be an integer");
}
}
return result;
}
And simply call that method, as
ArrayList<Integer> resultList = getIntegerArray(strArrayList); //strArrayList is a collection of Strings as you defined.
Happy coding :)
How about this one
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class sample7
{
public static void main(String[] args)
{
ArrayList<String> strArrayList = new ArrayList<String>();
strArrayList.add("1");
strArrayList.add("11");
strArrayList.add("111");
strArrayList.add("12343");
strArrayList.add("18475");
List<Integer> newList = new ArrayList<Integer>(strArrayList.size()) ;
for (String myInt : strArrayList)
{
newList.add(Integer.valueOf(myInt));
}
System.out.println(newList);
}
}
You're trying to cast an array of ArrayList objects to an int. Of course you get an error.
First of all, you want a plain old ArrayList
, not an array of ArrayList
s.
Second, you use Integer.parseInt()
to turn String
objects into int
s. int
is a primitive type, not a class type, and certainly not a superclass of String
.
You can cast list of strings to ints like this:
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i = 0; i < strArrayList.size(); i++) {
numbers.add(Integer.parseInt(strArrayList.get(i)));
}
Iterator on the list and parse them into Integers:
(WARN: not tested)
ArrayList<String> strArrayList;
int[] ArrayRes = new int[strArrayList.size()];
int i = 0;
for (String s : strArrayList)
{
ArrayRes[i++] = Integer.parseInt(s);
}
You can then convert them to a single int value based on how you wish to concatenate them.
精彩评论