Reputation: 558
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
The problem i'm having, is the nested lists ("relatedFiles") contain seperate instances of the Files, so in reality it's more like:
FileCabinet1
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.
Upvotes: 2
Views: 123
Reputation: 23903
There is an quite fast way to do this, putting all files in a set and build the related files again. Like this:
Map<File, File> existingFiles = new Map<File, File>();
for (File f : filesInCabinet) {
existingFiles.put(f, f);
}
for (File f : filesInCabinet) {
List<File> relatedFiles = f.getRelatedFiles();
for (int i = 0; i < relatedFiles.size(); i++) {
File relatedFile = existingFiles.get(relatedFiles.get(i));
relatedFiles.set(i, relatedFile);
}
}
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.
Upvotes: 1