0

我有一个自定义 ArrayList 并想将其转换为 CharSequence []。

我试过这个

List<String> list = Arrays.asList("foo", "bar", "waa");
CharSequence[] cs = list.toArray(new CharSequence[list.size()]);
System.out.println(Arrays.toString(cs)); // [foo, bar, waa]

但它只适用于字符串类型。

4

2 回答 2

6

我就是这样解决的

ArrayList<customtype> dir = new ArrayList<customtype>();
ArrayList<String> listing = new ArrayList<String>();
    customtype item;
    for(int i=0;i<dir.size();i++)
    {
        item = dir.get(i);
        listing.add(item.getPath()); 
    //getPath is a method in the customtype class which will return value in string format

      }
final CharSequence[] fol_list = listing.toArray(new CharSequence[listing.size()]);
//fol_list will have all the strings from getPath();
于 2013-12-25T06:50:20.810 回答
0

所以对于其他类型,您需要将每个项目转换为一个字符串:

ArrayList<CustomType> datas = new ArrayList<CustomType>();
....
ArrayList<String> strs = new ArrayList<String>();
for(CustomType data : datas) {
    strs.add(data.toString())
}

如果 CustomType 是您自己的类,请确保您已重载 toString() 方法

于 2013-12-25T07:02:40.233 回答