Java: Getting A String From An Arraylist

34,626

Solution 1

You need to increment the loop control variable.

for(int i=0; i<arraylist.size();i++){
   string.append(arraylist.get(i).toString());
}

Or

for(Object str:arraylist){
  string.append(str.toString());
} 

Solution 2

You're using i1 in your loop, but you're accessing element i.

This confusion is probably caused by using non-descriptive variable names. For example, I see array and arraylist - are those supposed to be the same?

So the first concern is just some code clean up. If that isn't the exact code, then show us what is. Also note that you can make a code block by indenting it all 4 spaces. Also a good idea to show us what the stack trace is.

Ideally, a small, complete program we can compile that shows us the error would generate the fastest corrective answer. You might even find the problem as you create that small program.

Solution 3

So many errors in just three lines of code. Really. Try this:

StringBuilder string = new StringBuilder();
for (int i1 = 0; i1 < arraylist.size(); i1++) {
    string.append(arraylist.get(i1).toString());
}

Or this:

StringBuilder string = new StringBuilder();
for (Object str : arraylist ) {
    string.append(str.toString());
}

Solution 4

I'd write it this way:

public static String concat(List<String> array, String separator) {
    StringBuilder builder = new StringBuilder(1024);
    for (String s : array) {
        build.append(s).append(separator);
    }
    return builder.toString();
}

Have you thought about how you'll keep each string separate in the concatenated version? Do want a space between each? This does not look very useful.

Share:
34,626
user1232105
Author by

user1232105

Updated on March 20, 2020

Comments

  • user1232105
    user1232105 about 4 years

    When I use a for loop(like so:)

      StringBuilder string = new StringBuilder();
        for(int i1 = 0; i1 < array.size()){
          string.append(arraylist.get(i).toString());
        } 
    

    I get an outOfBouds crash. I need to read the arraylist object by object, so arraylist.toString() does no good.

    any help? Thanks