I am quite confused because I have been given the task to display a List<E>
with the format [E1,E2,E3] and a SortedSet<E>
with the format {E1, E2, E3}, I have Overriden the toString method for my type of objects, but I do not know how to replace the squared braces with curly ones when the return type of the method I call toString()
on is of type SortedSet<E>
, I know that I can use toString.replace()
, problem is I cannot use it on my unit tests, I'm only allowed to call toString()
in those, any idea is greatly appreciated.
Edit, here's the code(I left it out intentionally before because it was in Italian on some points and I didn't want to confuse people more):
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;
}
This is what an example of a unit test would look like
@Test
public void testGetContenutoOrdinatoPerNome(){
assertEquals("{E1, E2, E3}",this.borsa.getContenutoOrdinatoPerNome().toString);
}
CodePudding user response:
I believe what you want is instanceof. something like:
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 "}";
}
This isn't actually based on what was calling your function, but what was passed in.
CodePudding user response:
You say you've tried anonymous inner classes but I'll put this proof of concept here for reference.
List<Integer> obj = new ArrayList<Integer>(){
public String toString(){
return "{}";
}
};
System.out.println(obj);//{}