I have implemented a program that stores sets within a Linkedlist. When I print out the linked lists, I get, for example, [1,2,3,4,5].
What I want is to change the square brackets to braces e.g. ‘{‘ & ‘}’
I can’t use string manipulations so I MUST override the toString method.
I am clueless on how to do this other than the fact I know i must create a subclass. It’s the method itself that baffles me.
public class outputSets
{
@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
public static void main(String args[])
{
LinkedList x0 = new LinkedList();
LinkedList x1 = new LinkedList();
LinkedList x2 = new LinkedList();
LinkedList x3 = new LinkedList();
LinkedList x4 = new LinkedList();
LinkedList x5 = new LinkedList();
LinkedList x6 = new LinkedList();
x0.add(new Integer(8));
for(int i=1; i<8; i++)
{
x1.add(new Integer(i));
}
x1.add((x0.getFirst()));
x2.addAll(x1);
x2.add(new Pair(1, x1));
x3.add(new Pair(x2,x1));
//x4.addAll(tree.union(x3, x2));
//x5.add(tree.difference(x4, x1));
//x6.add(tree.intersection(x4, x1));
/*
Iterator i0 = x0.listIterator();
Iterator i1 = x0.listIterator();
Iterator i2 = x0.listIterator();
Iterator i3 = x0.listIterator();
Iterator i4 = x0.listIterator();
Iterator i5 = x0.listIterator();
Iterator i6 = x0.listIterator();
*/
System.out.print(x0.getFirst());
System.out.println();
SetArray(x1);
System.out.println();
SetArray(x2);
System.out.println();
System.out.println();
}
@SuppressWarnings("rawtypes")
private static void SetArray(LinkedList x0)
{
for(int index=0; index < x0.size() ; index++)
{
if (index == 0)
{
System.out.print(x0.get(index));
}
else
{
System.out.print(", " +
"" + x0.get(index));
}
}
}
}
The output is completely dependent on the implementation of
AbstractCollection.toString()– whichLinkedList(and most other collections except maps) inherits. This implementation looks like this (slightly simplified):Having this as a guideline it should be pretty straightforward for you to create your own implementation that does not include square brackets. You can either create your own collection that overrides
toString()or have a separate utility method taking yourLinkedList inputas an argument (in that case obviously replaceiterator()withinput.iterator()).