I have an interesting dilemma:
I’ve got a class, let’s say it’s called FileCabinet.
The FileCabinet stores a LinkedList of Files, called “filesInCabinet”.
Inside each File, there is yet another LinkedList of Files, called “relatedFiles”.
So it kind of looks something like this for example:
FileCabinet1
- File1
- File3
- File2
- File3
- File4
- File3
- File1
- File2
- File4
- File2
The problem i’m having, is the nested lists (“relatedFiles”) contain seperate instances of the Files, so in reality it’s more like:
FileCabinet1
- File1
- File3_duplicate
- File2
- File3_duplicate2
- File4_duplicate
- File3
- File1_duplicate
- File2_duplicate
- File4
- File2_duplicate2
With this, when I go to change a property of a File in one of the nested Lists, I want it to change the property of the real File too, but it only changes the duplicate’s property.
Is there an efficient way I can ‘match-up’ the Files within the nested Lists to the non-nested List of Files? Each File also contains unique Strings, Integers and such, so it’s easy to determine which File a duplicate is a clone of.
There is an quite fast way to do this, putting all files in a set and build the related files again. Like this:
It works just putting files into a map and replacing the files on the related list with the one that is got from Map due the equals / hashcode implementation, so when you provide a related object you get the instance from the main list (filesInCabinet).
This means hashCode and equals needs to be implemented on File.