Java: getting string from Arraylist

When I use a for loop (for example: :)

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

I get outOfBouds crashing. I need to read an arraylist object by object, so arraylist.toString() does nothing good.

any help? Thanks

+4
source share
5 answers

You need to increase 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()); } 
+3
source

You use i1 in your loop, but you get access to element i .

This confusion is probably caused by the use of names without descriptive variables. For example, do I see array and arraylist - those that should be the same?

So, the first problem is just clearing the code. If this is not an exact code, then show us what it is. Also note that you can make a block of code by deferring all 4 spaces. It's also a good idea to show us what a stack trace is.

Ideally, a small, complete program that we can compile that shows us that the error will create the fastest corrective answer. You can even find a problem when creating this small program.

+2
source

So many errors in just three lines of code. Indeed. Try the following:

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

Or that:

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

I would write like this:

 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 to save each line separately in the concatenated version? Do you need space between them? This is not very helpful.

+1
source

If you use an Object of any type, you need to override the toString () method. and put the line where you want to add the line.

0
source

Source: https://habr.com/ru/post/1402351/


All Articles