Converting 'ArrayList to 'String[]' in Java

前端 未结 16 1500
情书的邮戳
情书的邮戳 2020-11-22 01:59

How might I convert an ArrayList object to a String[] array in Java?

16条回答
  •  情歌与酒
    2020-11-22 02:43

    Generics solution to covert any List to String []:

    public static   String[] listToArray(List list) {
        String [] array = new String[list.size()];
        for (int i = 0; i < array.length; i++)
            array[i] = list.get(i).toString();
        return array;
    }
    

    Note You must override toString() method.

    class Car {
      private String name;
      public Car(String name) {
        this.name = name;
      }
      public String toString() {
        return name;
      }
    }
    final List carList = new ArrayList();
    carList.add(new Car("BMW"))
    carList.add(new Car("Mercedes"))
    carList.add(new Car("Skoda"))
    final String[] carArray = listToArray(carList);
    

提交回复
热议问题