Home > Software design >  Find the value by key in Java
Find the value by key in Java

Time:02-17

I have two methods:

public Person signIn(String login, String password) {
        GenericTuple<String,String> pair = new GenericTuple<>(login,password);
        Person p = dataSource.getMapUsers().get(pair);
        return dataSource.getMapUsers().get(pair);
    }
    public void registration(Person person) {
        GenericTuple<String,String> pair = new GenericTuple<>(person.getLogin(),person.getPassword());
        dataSource.getMapUsers().put(pair,person);
    }

The code for GenericTuple is:

 public final class GenericTuple<F, S> {
    private final F first;
    private final S second;

    public GenericTuple(F first, S second) {
        this.first = first;
        this.second = second;
    }

    public F getFirst() {
        return first;
    }

    public S getSecond() {
        return second;
    }

    @Override
    public String toString() {
        return "Tuple(first="   first   ", second="   second   ")";
    }

}

After adding new element to my map(method "registration") i see in mapUsers new key and value.But in method signIn after registration the returning value of .get(pair) is null.Why this?

CodePudding user response:

Instead of using GenericTuple as the map's key, you should use login id as the key.

I don't think it is correct if you use GenericTuple as key. What if 2 Generic Tuples have the same login id, but different password (change password scenario perhaps), do you consider them equal and have the same hashcode?

  • Related