Reputation: 5177
I have a Object that contains an ArrayList of self referntial objects. Each Object in that ArrayList contains the same structre upto n degrees. Now i have to search for a string in the structure and if found i have to print all the way up to the root. Here is a sample
MyClass {
string name;
ArrayList<MyClass> subClasses;
}
What data structure would be best to do this. Or do i not need one to use it.
Kind Regards
Upvotes: 3
Views: 128
Reputation: 135992
This is http://en.wikipedia.org/wiki/Composite_pattern. Try my version
static class MyClass {
String name;
List<MyClass> subClasses;
MyClass(String name) {
this.name = name;
}
String search(String s, String path) {
if (!path.isEmpty()) {
path += "->";
}
path += name;
if (!s.equals(name)) {
if (subClasses == null) {
return null;
}
for (MyClass c : subClasses) {
return c.search(s, path);
}
}
return path;
}
}
public static void main(String[] args) throws Exception {
MyClass c1 = new MyClass("c1");
MyClass c2 = new MyClass("c2");
MyClass c3 = new MyClass("c3");
c1.subClasses = Arrays.asList(c2);
c2.subClasses = Arrays.asList(c3);
System.out.println(c1.search("c3", ""));
}
output
c1->c2->c3
Upvotes: 1
Reputation: 8865
You could have a method on MyClass like below
public List<String> findPathOfName(String nameToFind) {
List<String> result = new ArrayList<String>();
if (nameToFind.equals(name)) {
result.add(name);
} else {
for (MyClass aSubClass: subClasses) {
List<String> subResult = aSubClass.findPathOfName(nameToFind);
if (!subResult.isEmpty()) {
result.add(name);
result.addAll(subResult);
break;
}
}
}
return result;
}
basically recursively go through the structure and find the path. Returned list would contain the path like personA/personB/etc..
Upvotes: 2