你能根据调用 toString() 的方法替换 char 吗
Can you replace char based on which method calls toString()
我很困惑,因为我的任务是显示格式为 [E1,E2,E3] 的 List<E>
和格式为 {E1, E2, E3 的 SortedSet<E>
},我已经为我的对象类型覆盖了 toString 方法,但是当我调用 toString()
的方法的 return 类型是类型时,我不知道如何用大括号替换方括号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);
}
我相信你想要的是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+"}";
}
这实际上不是基于调用函数的内容,而是传入的内容。
你说你试过匿名内部 类 但我会把这个概念证明放在这里供参考。
List<Integer> obj = new ArrayList<Integer>(){
public String toString(){
return "{}";
}
};
System.out.println(obj);//{}
我很困惑,因为我的任务是显示格式为 [E1,E2,E3] 的 List<E>
和格式为 {E1, E2, E3 的 SortedSet<E>
},我已经为我的对象类型覆盖了 toString 方法,但是当我调用 toString()
的方法的 return 类型是类型时,我不知道如何用大括号替换方括号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);
}
我相信你想要的是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+"}";
}
这实际上不是基于调用函数的内容,而是传入的内容。
你说你试过匿名内部 类 但我会把这个概念证明放在这里供参考。
List<Integer> obj = new ArrayList<Integer>(){
public String toString(){
return "{}";
}
};
System.out.println(obj);//{}