1

I have a List of objects, which are either files or folders. They all contain a path as a string. How can I sort these into a hierarchy? If I have a folder objects that can hold folders and files and a regular file object, using a list of objects with their paths, how do I sort these into the folder and file objects?

Thanks in advance.

gkgkgkgk
  • 707
  • 2
  • 7
  • 26

1 Answers1

1

With the composite pattern, you can easily represent that.

You could have as base class Resource and File and Folder, subclasses of Resource.
And the hierarchical notion would rely on Folder that composes a Set of Resource that can be so File and Folder.
String path and reference to the physical resource fields could be stored in Resources as these have the same representation in both subclasses.

To go further, as you represent data, generally you also want to manipulate them and preferably in a simple and uniform way.
For example as clients want to perform common operations on resource instances (folder or a file) : creating, listing or deleting a resource, etc... it would be simpler for them if they can manipulate a single interface.
The composite pattern allows it.
Just declare in the base class (Ressource) the common operations and let subclasses to define the required behaviors. That's all.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Right, thanks so much. I have already set up the resource class and two subclasses... you make an interesting point about the uniform actions of parents on children objects... thanks so much. I think I figured out an efficient way to sort them – gkgkgkgk Dec 15 '17 at 21:02
  • 1
    You are welcome. So, you seem to be in the right way. Fine. – davidxxx Dec 15 '17 at 21:08
  • I have one more 'quick' question, I have found some serious flaws in my sorting algorithm. How would you go about sorting children into parents when there is a possibility of an infinite amount of parents? Nested folders withing nested folders, etc..... I seem to be having trouble getting past that first part. – gkgkgkgk Dec 17 '17 at 01:36
  • Like that, I cannot really see your sorting algorithm issue. Is it not working ? Is it too slow ? Whatever the number of directory, the idea is to start from a directory and to iterate on each one of its direct children. And as this one is also a folder, iterate on each one of its direct children. If your issue is not solved, I think that it would be simpler if you opened a new question with this specific issue. I am sure someone will be able to help you. And if nobody, I could look at. – davidxxx Dec 17 '17 at 08:34
  • right so the issue is that the objects dont come with their children assigned to them, they all come separately. I found this question which is very close to mine: https://stackoverflow.com/questions/1005551/construct-a-tree-structure-from-list-of-string-paths – gkgkgkgk Dec 17 '17 at 13:40