Java 如何连接ArrayList<;字符串>;到另一个字符串?

Java 如何连接ArrayList<;字符串>;到另一个字符串?,java,string,arraylist,concatenation,Java,String,Arraylist,Concatenation,我有一个包含这些字段的State类 String name; City capital; ArrayList<String> neighbors; 我正试图在州里测试这种方法 State ME = new State("ME", augusta, MEneighbors ); 奥古斯塔是一座有明确定义的城市,梅内堡是一位具有 MEneighbors.add("NH"); 这是我目前的测试 t.checkExpect(ME.toString(), "new State(M

我有一个包含这些字段的State类

String name;
City capital;
ArrayList<String> neighbors;
我正试图在州里测试这种方法

State ME = new State("ME", augusta, MEneighbors );
奥古斯塔是一座有明确定义的城市,梅内堡是一位具有

MEneighbors.add("NH");
这是我目前的测试

t.checkExpect(ME.toString(),
    "new State(ME, " + augusta.toString() + ", " + [NH] + ")");
我不太明白这为什么不起作用。它一直工作到ArrayList MEneighbors。如何将ArrayList添加为字符串


非常感谢

定义toString方法时,调用ArrayList的方法,如下所示

public String toString(){
return ("new State(" + 
    this.name  + ", " + 
    this.capital + ", " + 
    this.neighbors.toString() + ")\n");
}
toString
方法

Returns a string representation of this collection. The string representation consists of 
a list of the collection's elements in the order they are returned by its iterator, 
enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", "
(comma and space). Elements are converted to strings as by String.valueOf(Object).

即使您将代码修复为:

t.checkExpect(ME.toString(),
    "new State(ME, " + augusta.toString() + ", " + "[NH]" + ")");
注:括号内加引号


您仍然忘记在右侧添加“\n”!因为您的toString方法最后添加了“\n”

这甚至可以编译吗?它怎么不工作?您得到的输出是否不正确?异常消息?
+[NH]+
这在这个世界上永远不会编译。ArrayList的默认值是吗。toString()不够?+[NH]+不编译,你想做什么
t.checkExpect(ME.toString(),
    "new State(ME, " + augusta.toString() + ", " + "[NH]" + ")");