5

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

0

5 Answers 5

4

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());
} 
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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

Comments

1

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.

Comments

0

If you are using Object of any type then you have to override toString() method. and supply the String in which you want to append the String.

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.