如何将ArrayList <string>连接到另一个String?</string>

时间:2013-11-15 22:44:37

标签: java string arraylist concatenation

我有一个包含这些字段的州级

String name;
City capital;
ArrayList<String> neighbors;

我有一个toString()方法

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

我正试图在状态

上测试这个方法
State ME = new State("ME", augusta, MEneighbors );

其中augusta是已定义的城市,而MEneighbors是带有

的ArrayList
MEneighbors.add("NH");

这是我到目前为止的测试

t.checkExpect(ME.toString(),
    "new State(ME, " + augusta.toString() + ", " + [NH] + ")");

我不太明白为什么这不起作用。它一直工作到ArrayList MEneighbors。如何将ArrayList添加为String?

非常感谢。

2 个答案:

答案 0 :(得分:2)

即使您将代码修改为:

t.checkExpect(ME.toString(),
    "new State(ME, " + augusta.toString() + ", " + "[NH]" + ")");

注意:括号内的引号。

你仍然忘记添加&#34; \ n&#34;在右边!因为你的toString方法添加&#34; \ n&#34;最后!

答案 1 :(得分:0)

定义toString方法时,为ArrayList调用toString方法,就像这样

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).