Java:从数组列表中获取字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9780619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Getting A String From An Arraylist
提问by user1232105
When I use a for loop(like so:)
当我使用 for 循环时(像这样:)
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.
我遇到了 outOfBouds 崩溃。我需要逐个读取 arraylist 对象,所以
arraylist.toString()
没有好处。
any help? Thanks
有什么帮助吗?谢谢
回答by corsiKa
You're using i1
in your loop, but you're accessing element i
.
您正在i1
循环中使用,但您正在访问 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?
这种混淆可能是由使用非描述性变量名称引起的。例如,我看到array
和arraylist
- 那些应该是一样的吗?
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.
所以第一个问题只是一些代码清理。如果那不是确切的代码,那么向我们展示什么是。另请注意,您可以通过将所有 4 个空格缩进来制作代码块。向我们展示堆栈跟踪是什么也是一个好主意。
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.
理想情况下,我们可以编译一个小的、完整的程序,向我们展示错误将生成最快的纠正答案。您甚至可能会在创建该小程序时发现问题。
回答by adatapost
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());
}
回答by duffymo
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.
您是否考虑过如何在串联版本中将每个字符串分开?想要每个之间有一个空间吗?这看起来不是很有用。
回答by óscar López
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());
}
回答by kundan bora
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.
如果您使用的是任何类型的 Object,那么您必须覆盖 toString() 方法。并提供要在其中附加字符串的字符串。