问题描述
Java中如何将ArrayList
转换为String
?
How to convert an ArrayList<Character>
to a String
in Java?
List.toString
方法将其返回为 [a,b,c]
字符串 - 我想去掉括号(等)并将其存储为 abc.
The List.toString
method returns it as [a,b,c]
string - I want to get rid of the brackets (etcetera) and store it as abc
.
推荐答案
您可以遍历列表并创建字符串.
You can iterate through the list and create the string.
String getStringRepresentation(ArrayList<Character> list)
{
StringBuilder builder = new StringBuilder(list.size());
for(Character ch: list)
{
builder.append(ch);
}
return builder.toString();
}
将 StringBuilder
的容量设置为列表大小是一个重要的优化.如果不这样做,某些 append
调用可能会触发构建器的内部大小调整.
Setting the capacity of the StringBuilder
to the list size is an important optimization. If you don't do this, some of the append
calls may trigger an internal resize of the builder.
顺便说一句,toString()
返回 ArrayList 内容的人类可读格式.花时间从中过滤掉不必要的字符是不值得的.它的实现明天可能会发生变化,您将不得不重写过滤代码.
As an aside, toString()
returns a human-readable format of the ArrayList's contents. It is not worth the time to filter out the unnecessary characters from it. It's implementation could change tomorrow, and you will have to rewrite your filtering code.
这篇关于将字符数组列表转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!