public class ConcreteEdgesGraph implements Graph {
private final Set vertices = new HashSet<>();
private final List> edges = new ArrayList<>();
// Abstraction function:
// 图以集合vertices作为点集edges中所有边权大于0的元素构成的集合作为边集
// Representation invariant:
// edges中每一元素的from,to都在vertices中
// edges中每一元素的weight均>=0
// edges中不存在两元素from和to均相同
// Safety from rep exposure:
// 只有方法vertices、sources、targets会返回可变类型
// 这些方法返回时都使用了防御性复制,不会产生别名问题
//.....
}
其toString()方法被重写如下
@Override
public String toString()
{
StringBuffer ans=new StringBuffer();
ans.append("We have "+vertices.size()+" verticesn"+
"use method vertices() to get the set of them.n");
ans.append("Here are the edges:n");
for(Edge e: edges)
{
if(e.getWeight()>0)
ans.append("From: "+e.getFrom()+" To: "+e.getTo()+" Weight: "+e.getWeight()+"n");
}
checkRep();
return ans.toString();
}
@Test
public void testToString()
{
StringBuffer groundTruth=new StringBuffer();
Graph graph=emptyInstance();
graph.set("aa","bb",1);
graph.set("bb","cc",2);
groundTruth=new StringBuffer();
groundTruth.append("We have "+3+" verticesn"+
"use method vertices() to get the set of them.n");
groundTruth.append("Here are the edges:n");
String ans=graph.toString();
int index=ans.indexOf("Here are the edges:n");
assertEquals(groundTruth.toString(),ans.substring(0,index+20));
ans=ans.substring(index+20);
Map> trueEdges=new HashMap<>();
Map nowTargets=new HashMap<>();
nowTargets.put("bb",1);
trueEdges.put("aa",nowTargets);
nowTargets=new HashMap<>();
nowTargets.put("cc",2);
trueEdges.put("bb",nowTargets);
assertTrue(checkEqual(trueEdges,ans));
}