Microsoft Interview Question
Software Engineer in TestsCountry: United States
Interview Type: In-Person
You can write an extension method for arraylists, like ToStringX() [unfortunately you cannot override its ToString - at least I think so!]
But this one should work as cl.ToStringX()
public static string ToStringX(this ArrayList array)
{
string s = "[";
foreach (object obj in array)
{
ArrayList inner = obj as ArrayList;
if (inner != null)
{
s += inner.ToStringX() + " ";
}
else
{
s += obj.ToString() + " ";
}
}
return s+"]";
}
ArrayList al = new ArrayList();
ArrayList bl = new ArrayList();
ArrayList cl = new ArrayList();
al.Add(2);
al.Add(1);
bl.Add(3);
bl.Add(4);
cl.Add(al);
cl.Add(bl);
foreach (ArrayList a in cl) {
foreach (int k in a) {
Console.WriteLine(k);
}
}
You just need to write a recursive method to print the ArrayList
Method Output() is used to print element to screen.
- g233007 September 19, 2012