当前位置: 代码迷 >> J2SE >> ArrayList转换为二维数组有有关问题
  详细解决方案

ArrayList转换为二维数组有有关问题

热度:281   发布时间:2016-04-24 02:29:01.0
ArrayList转换为二维数组有问题
自定义了一个Person类, 里面有ID,name,address,telephone字段;我现在有一个List对象,大致数据有
{001,zhangsan,beijing,110;
002,lisi,shanghai,120;
003,wangwu,119;}
请问我该如何把它转成一个String类的字符串数组,方便我调用?
我使用的方法是
  public static void main(String[] args) {  
  List<Person> persons = ListTest.getPersons();  
   
  int n=persons.size();
  String[][] myArray=new String[n][]; //定义二维数组
  for (int i=0;i<n;i++) //构造二维数组
  {
  List<Person> tempArray= (List<Person>)persons.get(i);
  myArray[i]=(String[])tempArray.toArray(new String[0]); //注意此处的写法
  }
  //遍历数组
  for(int i=0;i<myArray.length;i++){
  for(int j=0;j<myArray[0].length;j++){
  System.out.println("myArray["+i+"]["+j+"]="+myArray[i][j]);
  }
  }
}


------解决方案--------------------
这是我提供的一个思路,不清楚你原来List是怎么存数据的
Java code
import java.util.List;import java.util.ArrayList;public class ShowPersons {    public static void main(String[] args) {        List<Person> persons = ListTest.getPersons();        int n=persons.size();        String[][] myArray=new String[n][]; //定义二维数组        for (int i=0;i<n;i++) //构造二维数组        {            Person tempArray= persons.get(i);            myArray[i]=tempArray.toStringAry(); //注意此处的写法        }        //遍历数组        for(int i=0;i<myArray.length;i++){            for(int j=0;j<myArray[0].length;j++){                System.out.println("myArray["+i+"]["+j+"]="+myArray[i][j]);            }        }    }}class ListTest{    public static List<Person>  getPersons(){        List<Person> persons=new ArrayList<Person>();        Person p1=new Person("001","zhangsan","beijing","110");        Person p2=new Person("002","lsi","shanghai","120");        Person p3=new Person("003","wangwu","guangzhou","119");        persons.add(p1);        persons.add(p2);        persons.add(p3);        return persons;    }}class Person{    private String ID;    private String name;    private String address;    public String[] toStringAry(){        String[] ary=new String[3];        if(ID!=null)            ary[0]=ID;        if(name!=null)            ary[1]=name;        if(address!=null)            ary[2]=address;        return ary;    }    public String getID() {        return ID;    }    public void setID(String ID) {        this.ID = ID;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    public String getTelephone() {        return telephone;    }    public void setTelephone(String telephone) {        this.telephone = telephone;    }    private String telephone;    public Person(){}    public Person(String ID, String name, String address, String telephone) {        this.ID = ID;        this.name = name;        this.address = address;        this.telephone = telephone;    }}
  相关解决方案