2011-10-10 155 views
5

我想要做的是需要转换ArrayList<String>[]ArrayList<Integer>[]的应用程序,我也用这个:转换的ArrayList <String>到一个ArrayList <Integer>或整数数组

ArrayList<String>[] strArrayList; 
int ArrayRes = (int) strArrayList[]; 

但是这个代码让我的错误,任何人都可以帮助我?

任何建议将赞赏名单上

+0

你怎么想字符串的ArrayList的数组转换成单个int?问题很模糊。 – HashimR

+0

Ali Ghanei,你想解析你的字符串arraylist到整数arraylist?简单地说,你问如何将你的ArrayList的所有字符串值转换为int值? –

+1

@HashimR答:问题并不清楚,它很清楚,我只是问我的问题。 –

回答

-7

迭代器,并把它解析为整数:

(警告:未测试)

ArrayList<String> strArrayList; 
int[] ArrayRes = new int[strArrayList.size()]; 

int i = 0; 
for (String s : strArrayList) 
{ 
    ArrayRes[i++] = Integer.parseInt(s); 
} 

然后,您可以将其转换为一个int值根据你希望如何连接它们。

+0

其要求的ArrayList转换为int不是int [] –

0

你想投的ArrayList对象的数组为int。当然你会得到一个错误。

首先,你需要一个普通的旧ArrayList,不是的ArrayList列数组。

其次,您使用Integer.parseInt()String对象转换为int s。 int是一个基本类型,而不是一个类类型,和肯定不是String一个超类。

-1

你可以施放字符串列表整数这样的:

ArrayList<Integer> numbers = new ArrayList<Integer>(); 

for(int i = 0; i < strArrayList.size(); i++) { 
    numbers.add(Integer.parseInt(strArrayList.get(i))); 
} 
+0

strArrayList [I]会给你一个'ArrayList'类型,这是不是'Integer.parseInt' – bdares

+0

的ArrayList 有效的参数????你确定 ??我认为这将是ArrayList的而ArrayList的

5

这个怎么样

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); 
     } 

    } 
11

定义,这将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. 

编码愉快:)

+0

谢谢你,它的工作了。 –

+0

使用'result.add(Integer.parseInt(stringValue.trim());'来避免空格造成不必要的异常错误。 – lifebalance

相关问题