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
Methods: Using get() method of ArrayList class. Using toArray() method of ArrayList class. Using copyOf() method of Arrays class.
An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.
Note: The ArrayList class does not have its own toString() method. Rather it overrides the method from the Object class.
indexOf() in Java. The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
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());
}
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.
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());
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With