0

I am working on a union-find algorithm, using the following :

HashMap<E,E> parent = new HashMap<E,E>();

I have written this method to find the last member of a family

    public E find(E src)
    {
        while (parent.get(src) != null)
            src = parent.get(src);
        return src;
    }

It works, but the thing is that I am going to work on this hashmap with big sets ; so I want to modify the find method so that it sets find(src) as the "father" of src. But I can't do that as it is, and I have the intuition of the reason why : if I try to do a copy in the beginning of the method

E copy = src;

And then at the end of the method

parent.put(copy,src);

It doesn't work because it does not actually do a "proper" copy. I have tried cloning parent but it doesn't work either.

Thank you all, and merry christmas !

  • That...at a glance, looks like it should work, but it's not supposed to do any copying. What about it doesn't work? – Louis Wasserman Dec 25 '15 at 20:54
  • 1
    I would not want to copy anything. IMO. E copy = src just makes another reference to src. now src points to the object and copy points to the same object... you would have to override the clone method to include all the members you want to clone... – DaveTheRave Dec 25 '15 at 21:19
  • DaveTheRave : yes that's what happens, it is a referencing more than a cloning, not sure how to go around it, will try your answer below and get back to you, thanks ! – colonelmoutarde Dec 26 '15 at 09:27

1 Answers1

0

Maybe this?

public E find(E src)

{
    E mysrc= src;
    while (parent.get(mysrc) != null)
        mysrc= parent.get(mysrc);
    parent.put(mysrc,src);
    return mysrc;
}
DaveTheRave
  • 463
  • 2
  • 5
  • Replaced `parent.put(mysrc,src)` to `parent.put(src,mysrc)` as otherwise the class representative would change each time, which is not exactly what we want. Anyway, it doesn't work, I think this doesn't address the referencing issue – colonelmoutarde Dec 26 '15 at 09:33