Can’t store Object in HashMap

I’m trying to create a SecureDataContainer with HashMap so defined: HashMap: ()>
Where KeyCouple is a class defined by me which contains the couple to access to the Vector associated to that couple. Now when i create a couple of HashMap in this method

private Map<KeyCouple,Vector<E>> DBUsers;

public void createUser(String Id, String passw) throws 
     UserAlreadyPresent {
     if(Id.isEmpty() || passw.isEmpty()) throw new IllegalArgumentException();
     if(existsUser(Id)) throw new UserAlreadyPresent(Id);

     KeyCouple u = new KeyCouple(Id, passw);
     DBUsers.put(u, new Vector<>());
}

Now, in main class, I Run the following code:

private static void testContainer(SecureDataContainer<String> container){
    try {
            container.createUser("Name","pwd");
    } catch (UserAlreadyPresent e) {
            System.out.println("User already present");
    }
...

To create the user “Name” with the Password “pwd”. But When i put something in the Vector associated to the couple created using my “put” method:

public boolean put(String Owner, String passw, E data) throws NoUserException {
    if(Owner == null || passw == null || data == null) throw new NullPointerException();
    if(Owner.isEmpty() || passw.isEmpty()) throw new IllegalArgumentException();

    KeyCouple user = new KeyCouple(Owner,passw);
    if(DBUsers.containsKey(user)){
        Vector<E> aux = DBUsers.get(user);
        return aux.add(data);
    }else{
        throw new NoUserException("No user");
    }
}

In main class, I call the method:

    try {
        container.put("Name", "pwd", someData of type E);
    } catch (NoUserException e){
        abort("no user");
    }

and it abort in every case, going even in the catch branch and printing “no user”.

What does this means?

Answer

You can check the sample KeyCouple class with equals and hashcode.

public class KeyCouple {   

    private String name;    

    private String pwd;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        KeyCouple keyCouple = (KeyCouple) o;
        return Objects.equals(name, keyCouple.name) &&
                Objects.equals(pwd, keyCouple.pwd);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, pwd);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *