可以根据哪个方法调用toString()来替换char吗



我很困惑,因为我被赋予了显示格式为[E1,E2,E3]的List<E>和格式为{E1,E2,E3}的SortedSet<E>的任务,我已经为我的对象类型重写了toString方法,但当我调用toString()的方法的返回类型为SortedSet<E>时,我不知道如何用花括号替换方括号,我知道我可以使用toString.replace(),问题是我不能在我的单元测试中使用它,我只能在这些测试中调用toString(),任何想法都将不胜感激。

编辑,这是代码(我之前故意省略了它,因为它在某些方面是意大利语的,我不想更多地混淆人们(:

public List<Attrezzo> getContenutoOrdinatoPerPeso(){
List<Attrezzo> out=new ArrayList<Attrezzo>();
out.addAll(this.attrezzi.values());
out.sort(new ComparatorePrimaPesoPoiNome());
return out;
}
public SortedSet<Attrezzo> getContenutoOrdinatoPerNome(){
SortedSet<Attrezzo> outAttrezzos= new TreeSet<Attrezzo>(new ComparatorePerNome());
outAttrezzos.addAll(this.attrezzi.values());
return outAttrezzos;
}

这就是一个单元测试的例子看起来像

@Test
public void testGetContenutoOrdinatoPerNome(){
assertEquals("{E1, E2, E3}",this.borsa.getContenutoOrdinatoPerNome().toString);
}

您说您尝试过匿名内部类,但我将把这个概念证明放在这里供参考。

List<Integer> obj = new ArrayList<Integer>(){
public String toString(){
return "{}";
}
};
System.out.println(obj);//{}

我相信您想要的是instanceof。类似于:

String makeString(Collection myCollection)
{
String stringedCollection = makeCommaSeparatedString(myCollection);
if(myCollection instanceof List)
{
// surround it with square brackets
return "["+stringedCollection+"]";
}
else if(myColleciton instanceof Set)
{
// surround with braces
return "{"+stringedCollection+"}";
}

这实际上并不是基于调用函数的内容,而是基于传入的内容

最新更新