Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Key type to be used with hash based Maps and Sets #182

Open
dmfs opened this issue Jan 6, 2019 · 0 comments
Open

Key type to be used with hash based Maps and Sets #182

dmfs opened this issue Jan 6, 2019 · 0 comments

Comments

@dmfs
Copy link
Owner

dmfs commented Jan 6, 2019

Having to implement the equals & hashable contracts for polymorphic types is often annoying a can be a real pain. In many cases it results in lots of duplicated code or code inheritance from abstract classes.
This approach also violates SRP and DRY principles.
This issue aims to provide an alternative way.

Instead of having each class implement the equals and hashable contracts a dedicated adapter could do the job. The interface might look somewhat like this:

public interface Key<T> extends Single<T>
{
    @Override
    boolean equals(Object other);

    @Override
    int hashCode();
}

Concrete subtypes would serve as the actual keys, like so:

public final class FooKey implements Key<Foo>
{
…
}

Now whenever you need to put an implementation of Foo into a Set or Map you use that key instead.

Set<FooKey> fooSet = new HashSet<>();
fooSet.add(new FooKey(afoo));
…
if (fooSet.contains(new FooKey(afoo)))
{
   …
}

Note the generic parameter of the Set is the concrete implementation FooKey because there may be other Key<Foo> implementations which are derived from a different Foo property and they are not necessarily compatible.

Key extends Single<T> to allow retrieval of the actual key when needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant