Question

I have a custom ArrayList and want to convert it into CharSequence[].

I tried this

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]

but it only works for string type.

Was it helpful?

Solution

This is how I solved it,

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

OTHER TIPS

So for other type, you need covert each item to a string:

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

If CustomType is yourself class, make sure you have overload the toString() method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top