Shaydoth Shaydoth - 4 months ago 12
Java Question

Dealing with equality in an ArrayList in java

Say I have this section of code:

for(int i = 0; i < accounts.size(); i++) {
if(UserID.equals(accounts.get(i).getUserID())) {
if(accounts.contains(accounts.get(i))) {
if(UserPass.equals(accounts.get(i).getPassword())) {
System.out.println("True");
}
} else {
typePhrase("unrecognised userID: '" + UserID + "'");
}
} else {
typePhrase("unrecognised userID: '" + UserID + "'");
}
}


It goes through an arrayList filled with objects, that have an ID and a password. I get two inputs from the user, one is the userID, and the other is the password. What I want is for it to go through every possible object that is saved in that arrayList, and if it finds a match, print
true
into the console, the issue that I'm having is that if you type in something wrong, it prints an message that it is unrecognised for every object in the arrayList. It also prints the message for every object that there is in the arrayList -1 if you type one in right. What do you suggest I do?

User class:

public class User {
String userID;
String password;

public User(String ID, String Pass) {
userID = ID;
password = Pass;
}

public String getUserID() {
return userID;
}

public String getPassword() {
return password;
}
}


EDIT:

ArrayList<User> accounts = new ArrayList<User>();

Answer

You should implement equals method in the User class:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    User user = (User) o;

    if (!getUserID().equals(user.getUserID())) return false;
    return getPassword().equals(user.getPassword());

}

Then you can create a new User with the typed information and just check if the list contains this User:

User user = new User("typedUserId", "typedPassword");
System.out.println(accounts.contains(user));