我想制作一个需要将ArrayList<String>[]
转换为ArrayList<Integer>[]
的应用程序,我还使用了以下代码:
ArrayList<String>[] strArrayList;
int ArrayRes = (int) strArrayList[];
但是这段代码出现了错误,有人能帮我吗?
任何建议都将不胜感激。
我想制作一个需要将ArrayList<String>[]
转换为ArrayList<Integer>[]
的应用程序,我还使用了以下代码:
ArrayList<String>[] strArrayList;
int ArrayRes = (int) strArrayList[];
但是这段代码出现了错误,有人能帮我吗?
任何建议都将不胜感激。
定义一个方法,将ArrayList中的所有字符串值转换为整数。
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;
}
只需要调用那个方法,如下:
ArrayList<Integer> resultList = getIntegerArray(strArrayList); //strArrayList is a collection of Strings as you defined.
愉快的编码 :)
result.add(Integer.parseInt(stringValue.trim());
来避免空格引起不必要的异常错误。 - lifebalance 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);
}
}
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i = 0; i < strArrayList.size(); i++) {
numbers.add(Integer.parseInt(strArrayList.get(i)));
}
ArrayList
类型,这不是Integer.parseInt
的有效参数。 - user684934在列表上进行迭代并将它们解析为整数:
(警告:未经测试)
ArrayList<String> strArrayList;
int[] ArrayRes = new int[strArrayList.size()];
int i = 0;
for (String s : strArrayList)
{
ArrayRes[i++] = Integer.parseInt(s);
}
然后,您可以根据希望连接它们的方式将它们转换为单个 int 值。