0

Hello fellow programmers,

In my app I just deserialized an ArrayList from a text file and now I have an ArrayList with Strings. For design purposes I want to put the contents of the ArrayList into one organized string with comas and spaces.

I made an attempt at it but he app forcecloses and the LogCat pinpoints the error to this code:

FYI: OptionsText is an empty string and ListOptions is the ArrayList with the strings.

public void getOptionsText(){
        int i;
        OptionsText=ListOptions.get(1);
        for(i=2; i<ListOptions.size(); i++){
            OptionsText = OptionsText + ", " + ListOptions.get(i);
        }
        Options.setText(OptionsText);
    }

3 Answers 3

1

Just use ArrayList#toString():

public void getOptionsText() {
    String OptionsText = ListOptions.toString();
    Options.setText(OptionsText.substring(1, OptionsText.length-1);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This assumes ListOptions is an ArrayList. What if ListOptions is a List? Since the List implementation is unknown ("program to the interface"), it would be better to use Arrays.toString.
@SteveKuo not really. It assumes that ListOptions is an AbstractCollection, an abstract class which pretty much every Java SE collection implementation inherits. Sure, a joiner (Guava/Apache Commons/other) would work; so would a hand-written method. Show me an existing library implementation with a different toString() output format; then, we'll talk.
0

can you please try this...check if list is not null...

list.toString().replace("[", "").replace("]", "");

1 Comment

This is actually worse than my answer, both in performance and correctness. What if one of the elements of the list's string form contains '[' or ']'?
0

Other than the other answers given by fellow SO users, you can also use the join method from the StringUtils class from org.apache.commons.lang.

OR

The join method from the Joiner class from com.google.common.base

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.