如何从ArrayList#toString()中删除括号[]? [英] How to remove the brackets [ ] from ArrayList#toString()?
问题描述
我在Java中创建了一个如下所示的数组列表:
I have created an Array List in Java that looks something like this:
public static ArrayList<Integer> error = new ArrayList<>();
for (int x= 1; x<10; x++)
{
errors.add(x);
}
当我打印错误时我得到错误
When I print errors I get it errors as
[1,2,3,4,5,6,7,8,9]
[1,2,3,4,5,6,7,8,9]
现在我要从此数组列表中删除方括号([])。我以为我可以使用方法errors.remove([),但后来我发现它只是布尔值并显示true或false。有人可以建议我怎么做到这一点?
Now I want to remove the brackets([ ]) from this array list. I thought I could use the method errors.remove("["), but then I discovered that it is just boolean and displays a true or false. Could somebody suggest how can I achieve this?
提前感谢你的帮助。
推荐答案
你是可能会调用系统。 out.println 打印列表。 JavaDoc说:
You are probably calling System.out.println to print the list. The JavaDoc says:
This method calls at first String.valueOf(x) to get the printed object's string value
括号由ArrayList的 toString
实现添加。要删除它们,您必须先获取字符串:
The brackets are added by the toString
implementation of ArrayList. To remove them, you have to first get the String:
String errorDisplay = errors.toString();
然后删除括号,如下所示:
and then strip the brackets, something like this:
errorDisplay = errorDisplay.substring(1, errorDisplay.length() - 1);
依赖 toString()$是不好的做法c $ c>实施。
toString()
仅用于生成用于记录或调试目的的人类可读表示。所以最好在迭代时自己构建String:
It is not good practice to depend on a toString()
implementation. toString()
is intended only to generate a human readable representation for logging or debugging purposes. So it is better to build the String yourself whilst iterating:
List<Integer> errors = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int x = 1; x<10; x++) {
errors.add(x);
sb.append(x).append(",");
}
sb.setLength(sb.length() - 1);
String errorDisplay = sb.toString();
请注意,这不是一个数组,只是一个显示列表内容的String。要从列表创建数组,可以使用 list.toArray():
Note that this is not an array, just a String displaying the contents of the list. To create an array from a list you can use list.toArray():
// create a new array with the same size as the list
Integer[] errorsArray = new Integer[errors.size()];
// fill the array
errors.toArray(errorsArray );
这篇关于如何从ArrayList#toString()中删除括号[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!