在arraylist中拆分值并存储在不同的数组列表中

时间:2012-04-15 14:28:10

标签: java android

我在android中做一个项目,我有一个问题我的数组列表值如此

[name1,addr1,place1,name2,addr2,place2]

如何拆分此值并希望将名称,地址,位置存储在不同的数组列表中?

3 个答案:

答案 0 :(得分:1)

ArrayList<String> allInfo, names, addresses, places;
//init everythin
for(int i=0; i<allInfo.size();i++)
  switch( i % 3 ){
     case 0:
        names.add(allInfo.get(i));
        break;
     case 1:
        addresses.add(allInfo.get(i));
        break;
     case 2:
        places.add(allInfo.get(i));
        break;
  }

或更有效的方法

for(Iterator itr=allInfo.iterator(), int i=0; itr.hasNext(); i++)
    switch( i % 3 ){
         case 0:
            names.add(itr.next());
            break;
         case 1:
            addresses.add(itr.next());
            break;
         case 2:
            places.add(itr.next());
            break;
      }

答案 1 :(得分:0)

您可以通过以下方式将数组拆分为不同的数组。

    ArrayList<String> mainArray = new ArrayList<String>();
    //mainArray Has Data now we want to shift it into different arrays
    ArrayList<String> name = new ArrayList<String>();
    ArrayList<String> address = new ArrayList<String>();
    ArrayList<String> place = new ArrayList<String>();
    for(int i=0;i<mainArray.size();i++){
        switch(i%3){
        case 0:
            name.add(mainArray.get(i));
            break;
        case 1:
            address.add(mainArray.get(i));
            break;
        case 2:
            address.add(mainArray.get(i));
            break;
        }
    }

答案 2 :(得分:0)

ArrayList<String> yourArrayList; //this is you array list which have names, addresses and places in it

ArrayList<String> names = new ArrayList<String>();
ArrayList<String> addresses = new ArrayList<String>();
ArrayList<String> places = new ArrayList<String>();

for(int i =0;i<yourArrayList.length;i++){ //iterate yourArrayList and for every element, add it in a seperate array list 
    if(i%3==0)
        names.add(yourArrayList[i])

    else if(i%3==1)
        addresses.add(yourArrayList[i]);

    else if(i%3==2)
        places.add(arraylist[i]);
}